如何在实现Condition/ConfigurationCondition接口的类中使用@Value或Environment [英] How get working @Value or Environment in a class implementing the Condition/ConfigurationCondition interfaces

查看:190
本文介绍了如何在实现Condition/ConfigurationCondition接口的类中使用@Value或Environment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仅使用JavaConfig.

I am working with only JavaConfig.

我有以下声明:

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

根据以下文章,它对于JavaConfig是必需的: Spring 3.2 @value纯Java配置的注解不起作用,但是Environment.getProperty起作用

it is mandatory for JavaConfig according with the following post: Spring 3.2 @value annotation with pure java configuration does not work, but Environment.getProperty works

以下代码可以完美运行(出于测试目的,许多@Values都可以实现):

The following code works perfect (many @Values by testing purposes):

@Configuration
public class ActiveMQServerConfiguration {

    @Value("${localhost.address}")
    private String localHost;

    @Value("${remotehost.address}")
    private String remoteHost;

    @Value("${localhost.port}")
    private Integer localPort;

    @Value("${remotehost.port}")
    private Integer remotePort;

    @Bean(name="connectionFactory")
    @Conditional(LocalHostStatusCondition.class)
    public ActiveMQConnectionFactory localConnectionFactory(
            @Value("${localhost.protocol}") String protocol,
            @Value("${localhost.address}") String host,
            @Value("${localhost.port}") String port ){

        System.out.println("protocol: "+protocol);
        System.out.println("host: "+host);
        System.out.println("port: "+port);

        System.out.println("localHost: "+localHost);
        System.out.println("localPort: "+localPort);
        System.out.println("remoteHost: "+remoteHost);
        System.out.println("remotePort: "+remotePort);

我可以在控制台/终端中看到

I can see in the console/terminal

Alpha

protocol: tcp
host: 127.0.0.1
port: 61616
localHost: 127.0.0.1
localPort: 61616
remoteHost: 192.168.1.34
remotePort: 61616

但是以下内容无法按预期进行:

But the following does not works how expected:

public class LocalHostStatusCondition implements Condition {

    private static final Logger logger = LoggerFactory.getLogger(LocalHostStatusCondition.class);

    @Value("${localhost.address}")
    private String localHost;

    @Value("${remotehost.address}")
    private String remoteHost;

    @Value("${localhost.port}")
    private Integer localPort;

    @Value("${remotehost.port}")
    private Integer remotePort;

    @Autowired
    private Environment environment;

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        logger.info("LocalHostStatusCondition...");

        System.out.println("localHost: "+localHost);
        System.out.println("localPort: "+localPort);
        System.out.println("remoteHost: "+remoteHost);
        System.out.println("remotePort: "+remotePort);
        System.out.println("Env..." + environment.getProperty("localhost.address", String.class) );

实际上是相同的,甚至可以在环境

Practically the same and even working with Environment

输出为:

测试版

localHost: null
localPort: null
remoteHost: null
remotePort: null
[WARNING] 
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.manuel.jordan.infrastructure.support.LocalHostStatusCondition.matches(LocalHostStatusCondition.java:42)

根据

条件必须遵循与BeanFactoryPostProcessor相同的限制,并注意切勿与Bean实例进行交互.要更精细地控制与@Configuration Bean交互的条件,请考虑 ConfigurationCondition 接口.

关于 ConfigurationCondition 我已经阅读了何时还要使用Spring @ConfigurationCondition和@Condition吗?

我已编辑以下内容:

public class LocalHostStatusCondition implements ConfigurationCondition {

…

    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.PARSE_CONFIGURATION;
    }

如果我使用:

  • ConfigurationPhase.REGISTER_BEAN 我得到的输出与 Beta
  • 相同
  • ConfigurationPhase.PARSE_CONFIGURATION; ,我没有任何错误,但是...
  • ConfigurationPhase.REGISTER_BEAN I get the same output how Beta
  • ConfigurationPhase.PARSE_CONFIGURATION; I get no errors but...

但是控制台/终端没有显示有关正在运行的句子的任何信息,我的意思是System.out没有打印出来(我不了解这种奇怪的行为).

but the console/terminal does not show nothing about the sentences working, I mean, System.out are not printing (I don't understand about this weird behaviour).

我该如何解决?

我需要工作@Value或Environment,目的是让应用程序知道是否应该连接到本地或远程ActiveMQ服务器.

I need have working @Value or Environment, it with the purpose to let know the application if should connect to a local or remote ActiveMQ server.

是的,我已阅读以下内容: 如何延迟对Spring @Conditional的评估配置注释? 似乎没有解决办法……

And yes, I have read the following: How do I delay evaluation of a Spring @Conditional configuration annotation? seems there is no solution…

谢谢

推荐答案

您拥有

@Conditional(LocalHostStatusCondition.class)

Spring采用您指定的Class类型,并将其实例化以使用其matches方法.它不会将实例视为bean,不会对其执行自动装配,也不会进行任何@Value处理.后者对于BeanFactoryPostProcessor也是适用的.

Spring takes the Class type you've specified and instantiates it to use its matches method. It doesn't consider the instance as a bean, it doesn't perform autowiring on it, nor any @Value processing. The latter are true for BeanFactoryPostProcessor as well.

如果需要,可以从ConditionContext中检索Environment.另一种方法是自己加载属性.

You can retrieve the Environment from the ConditionContext if you want to. The alternative is to load the properties yourself.

这篇关于如何在实现Condition/ConfigurationCondition接口的类中使用@Value或Environment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆