【问题标题】:Referring applicationContext.xml bean in Spring @Configuration在 Spring @Configuration 中引用 applicationContext.xml bean
【发布时间】:2015-04-23 00:55:21
【问题描述】:

我有这样的事情:

    @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;

感谢您的宝贵时间!

【问题讨论】:

    标签: java spring spring-annotations


    【解决方案1】:

    如何在 @Configuration 中引用这些 bean?

    根据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 { ...
    

    让我有 50 多个属性。有没有比为每个属性定义类似以下内容更好的方法来引用它们?

    没有,我可以想象 :-( ...您如何“更好地访问” 50 多个属性,而不是“按名称”-“按索引”,类似数组!?虽然有些属性可以耦合,归根结底”,每个都有(应该)有其特殊的含义和目的 - 并且针对那些单独触摸/连接/配置的。(最佳实践技巧就是尽可能少地这样做)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 2015-10-08
      • 1970-01-01
      • 2012-11-15
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多