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

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

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

&lt;bean id=&quot;myEnvironmentProcessor &quot; class=&quot;com.example.MyEnvironmentProcessor&quot;&gt;
    &lt;constructor-arg&gt;
        &lt;bean class=&quot;org.springframework.core.env.Environment&quot;/&gt;
    &lt;/constructor-arg&gt;
&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)而不是引用其类来引用环境:

<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中有一个空格字符;&quot;myEnvironmentProcessor &quot;

英文:

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

&lt;bean id=&quot;myEnvironmentProcessor&quot; class=&quot;com.example.MyEnvironmentProcessor&quot;&gt;
    &lt;constructor-arg ref=&quot;environment&quot;/&gt;
&lt;/bean&gt;
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; &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:

确定