2017-03-01 5 views
0

私はスレッドを拡張するクラスを持っています。各スレッドは、独自のHTTPサーバーに接続します。スレッドスコープのSpring Bean - 可能でしょうか?

Spring Beanを設定し、スレッドごとにカスタムドメインを渡す方法は?

私が知る限り、Springはそのようなスコープをサポートしています:シングルトン、プロトタイプ、セッション、リクエスト。

答えて

0

プロパティに基づいてスレッドのリストを挿入できます。

スレッドクラスです。

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 

Configクラス:

@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(); 
     }