【问题标题】:Thread scoped Spring Bean - is it possible?线程范围的 Spring Bean - 有可能吗?
【发布时间】:2017-03-01 18:30:10
【问题描述】:

我有一个扩展 Thread 的类。每个线程都连接到自己的 HTTP 服务器。

如何配置 Spring Bean 并为每个线程传递自定义域?

据我所知,Spring 支持这样的范围:单例、原型、会话、请求。

【问题讨论】:

    标签: java spring javabeans


    【解决方案1】:

    您可以根据属性注入线程列表。像这样:

    线程类。

    public class MyThread implements Runnable{
    
        private String domain; 
    
        public MyThread(String domain) {
            this.domain = domain;
        }
    
        @Override
        public void run() {
            System.out.println(domain);
        }
    
    }
    

    属性文件:

    t1.domain=www.domain1.com
    t2.domain=www.domain2.com
    

    配置类:

    @Configuration
    @PropertySource(value="classpath:test.properties", name="testProperties")
    public class Config {
    
        @Autowired
        private Environment env;
    
        @Bean
        public List<MyThread> myThreads(){
            List<MyThread> list = new ArrayList<>();
            for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
                org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) it.next();
    
                if ("testProperties".equals(propertySource.getName())) {
                    for(String propertyName : ((MapPropertySource) propertySource).getPropertyNames()){
                        list.add(new MyThread(propertySource.getProperty(propertyName).toString()));
                    }
                }
            }
            return list;
        }
    }
    

    使用线程的类:

    List<MyThread> ll = (List<MyThread>)context.getBean("myThreads");
            for(MyThread t : ll){
                Thread th = new Thread(t);
                th.start();
            }
    

    【讨论】:

      猜你喜欢
      • 2012-07-06
      • 2011-02-23
      • 2013-07-10
      • 1970-01-01
      • 2018-12-26
      • 2015-09-03
      • 2011-07-28
      • 2011-05-06
      相关资源
      最近更新 更多