如何将Spring Boot环境Bean注入自定义的Spring XML Bean?

huangapple go评论95阅读模式
英文:

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

问题

  1. <bean id="myEnvironmentProcessor" class="com.example.MyEnvironmentProcessor">
  2. <constructor-arg>
  3. <bean class="org.springframework.core.env.Environment" />
  4. </constructor-arg>
  5. </bean>
英文:

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

  1. @Configuration
  2. public class CustomConfiguration {
  3. @Bean
  4. public MyEnvironmentProcessor myEnvironmentProcessor(Environment env) {
  5. return new MyEnvironmentProcessor(env);
  6. }
  7. }

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

  1. &lt;bean id=&quot;myEnvironmentProcessor &quot; class=&quot;com.example.MyEnvironmentProcessor&quot;&gt;
  2. &lt;constructor-arg&gt;
  3. &lt;bean class=&quot;org.springframework.core.env.Environment&quot;/&gt;
  4. &lt;/constructor-arg&gt;
  5. &lt;/bean&gt;

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)而不是引用其类来引用环境:

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

顺便提一下,你的bean定义中在ID中有一个空格字符;&quot;myEnvironmentProcessor &quot;

英文:

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

  1. &lt;bean id=&quot;myEnvironmentProcessor&quot; class=&quot;com.example.MyEnvironmentProcessor&quot;&gt;
  2. &lt;constructor-arg ref=&quot;environment&quot;/&gt;
  3. &lt;/bean&gt;
  1. import org.springframework.core.env.Environment;
  2. public class MyEnvironmentProcessor {
  3. private Environment environment;
  4. public MyEnvironmentProcessor(Environment environment) {
  5. this.environment = environment;
  6. }
  7. }

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

huangapple
  • 本文由 发表于 2020年9月16日 15:58:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63915584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定