java - 在 Spring @Configuration 中引用 applicationContext.xml bean

标签 java spring spring-annotations

我有这样的东西:

    @Configuration
    public class SpringConfigUtil {

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


        @Value("#{ systemProperties['activemq.username'] }") 
        private String userName;

        @Value("#{ systemProperties['activemq.password'] }") 
        private String password;

        @Value("#{ systemProperties['activemq.URL'] }") 
        private String brokerURL;

        @Value("#{ systemProperties['activemq.queueName'] }") 
        private String queueName;


         @Bean
         public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();

         }


        @Bean(name="producer")

        public JmsTemplate jmsTemplate() {
            JmsTemplate jmsTemplate = new JmsTemplate();
            jmsTemplate.setDefaultDestination(new ActiveMQQueue(queueName));
            jmsTemplate.setConnectionFactory(connectionFactory());
            return jmsTemplate;
        }


        @Bean
        public ActiveMQConnectionFactory connectionFactory() {
            ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
            activeMQConnectionFactory.setBrokerURL(brokerURL);
            activeMQConnectionFactory.setUserName(userName);
            activeMQConnectionFactory.setPassword(password);          
            return activeMQConnectionFactory;
        }
    }

效果很好。 假设我还有一个 applicationContext.xml 文件,它已加载一些 bean。

我如何在@Configuration中引用这些bean? 我不想再次以编程方式创建 bean,因为它们已经通过加载 applicationContext.xml 创建了。

让我拥有 50 多个属性。有没有比为每个属性定义如下更好的方法来引用它们?

  @Value("#{ systemProperties['activemq.URL'] }") 
    private String brokerURL;

感谢您的宝贵时间!

最佳答案

How do I refer to those beans here in @Configuration?

根据http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch06.html ,请尝试:

...
@Configuration
@AnnotationDrivenConfig // enable the @Autowired annotation (??)
@ImportXml("classpath:<*path*/to/your/*>applicationContext.xml")
public class SpringConfigUtil { ...
<小时/>

Let's have I have 50+ properties. Is there a better way to refer to them than defining something like the following for every property?

没有,我可以想象:-(...你怎么能比“通过它们的名字”-“通过索引”,类似数组“更好地访问”50多个属性!?虽然有些属性可以耦合,归根结底,“每个都有(应该有)其特殊的含义和目的 - 并且对于单独的触摸/连接/配置。(最佳实践技巧是尽可能少做)

关于java - 在 Spring @Configuration 中引用 applicationContext.xml bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29811676/

相关文章:

java - @Async 与 outstream 和 thread.sleep 方法

java - 二元矩阵查找距离为 k 的所有单元格

java - JVM-XX :+StringCache argument?

java - 可点击的jbutton,如果是java的话

java - 什么是ActionMapping、RenderMapping?

java - Spring REST 应用程序中身份验证的最佳方式

java - 在 SonarQube 中使用 Spring 构造函数注入(inject)

java - 创建一个数组,其中包含一定范围内的随机值

spring - 通过 Grail 的 bean DSL 配置 Jackson 的 ObjectMapper

java - 带有动态参数的自定义注释