如何在Spring 5中使用环境创建<bean>标签

时间:2019-01-29 17:10:49

标签: xml spring annotations autowired applicationcontext

在Spring中,您可以使用注释执行以下操作:

@Configuration
@PropertySource(value = "classpath:props.properties")
public class MyConfiguration {
    @Autowired
    Environment env;

    @Bean
    public MyBean myBean() {
        MyBean myBean = new MyBean;
        myBean.setEnv(env);
    }
}

是否可以通过XML注入环境? 我想要类似的东西:

<context:property-placeholder location="classpath:props.properties"/>
<bean id="env" class="org.springframework.core.env.Environment"/>
<bean id="myBean" class="MyBean" p:env-ref="env"/>

但是我不知道是否可以从XML中声明的myBean bean中的env bean引用中获取属性。

1 个答案:

答案 0 :(得分:0)

最后,我发现可以使用XML配置在MyBean中实现EnvironmentAware以获得环境。