Search code examples
javaspringspring-bootspring-context

How to inject Spring boot Environment bean to Custom Spring xml bean?


I created a bean using spring boot @Configuration class annotation like below

@Configuration
public class CustomConfiguration {
    @Bean
    public MyEnvironmentProcessor myEnvironmentProcessor(Environment env) {
        return new MyEnvironmentProcessor(env);
    }
}

In one of the application I am using Spring XML to create the bean then loading them using Spring boot there I am trying to create the same bean in XML but it was not working, I tried below

<bean id="myEnvironmentProcessor " class="com.example.MyEnvironmentProcessor">
    <constructor-arg>
        <bean class="org.springframework.core.env.Environment"/>
    </constructor-arg>
</bean>

How to create an equivalent Java based bean in Spring XML?

Spring version: 5.2.4.RELEASE Spring boot version: 2.2.5.RELEASE


Solution

  • You can refer to the environment by referencing its ID, which is environment, instead of its class:

    <bean id="myEnvironmentProcessor" class="com.example.MyEnvironmentProcessor">
        <constructor-arg ref="environment"/>
    </bean>
    
    import org.springframework.core.env.Environment;
    
    public class MyEnvironmentProcessor {
        private Environment environment;
    
        public MyEnvironmentProcessor(Environment environment) {
            this.environment = environment;
        }
    }
    
    

    By the way, your bean definition has a space character in the ID; "myEnvironmentProcessor "