英文:
How to inject Spring boot Environment bean to Custom Spring xml bean?
问题
<bean id="myEnvironmentProcessor" class="com.example.MyEnvironmentProcessor">
<constructor-arg>
<bean class="org.springframework.core.env.Environment" />
</constructor-arg>
</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
答案1
得分: 1
你可以通过引用其ID(environment
)而不是引用其类来引用环境:
<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;
}
}
顺便提一下,你的bean定义中在ID中有一个空格字符;"myEnvironmentProcessor "
。
英文:
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 "
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论