2017-03-01 1 views
0

J'ai une classe qui étend le fil. Chaque thread se connecte à son propre serveur HTTP.Haricot de printemps fileté - est-ce possible?

Comment configurer Spring Bean et passer un domaine personnalisé pour chaque thread? Pour autant que je sache, Spring prend en charge de telles portées: singleton, prototype, session, request.

Répondre

0

Vous pouvez injecter une liste de threads en fonction des propriétés. quelque chose comme ceci:

La classe de thread.

public class MyThread implements Runnable{ 

    private String domain; 

    public MyThread(String domain) { 
     this.domain = domain; 
    } 

    @Override 
    public void run() { 
     System.out.println(domain); 
    } 

} 

Le fichier de propriétés:

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

La classe de configuration:

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

La classe qui utilise les fils:

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