[英]JavaConfig Spring make beans available to all application
我有一個主要方法的罐子。 我用@Configuration注釋創建了一個Java配置。
@Configuration
@ComponentScan(basePackages = { "com.test.commons" })
public class ProxyConfig {
}
在此com.test.commons中,我提供了一項服務
package com.test.commons;
@Service
public class RestService {
//do rest calls
public String restGetCall(URL url){
...
}
}
我不是要這個
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(ProxyConfig.class);
context.getBean("myBean");
主要的
@SpringBootApplication(scanBasePackages={"com.test.commons", "com.test.soapproxy" })
public class MainAppProxy
{
private final static Logger logger = LoggerFactory.getLogger(MainAppProxy.class);
public static void main( String[] args )
{
SpringApplication.run(MainAppProxy.class, args);
// Choose environment from the arguments
String env = args[0];
// publish an endpoint here
Configuration config = null;
config = configs.properties
(new File("config_"+env+".properties"));
Endpoint.publish(endpointAddress, new SomeProxyImpl(config));
我嘗試注入Bean的類(這里真的需要@Component嗎?)
@Component
public class SomeProxyImpl implements SomeServiceSoap {
@Autowired RestService restService;
我希望能夠通過@Autowired在我的所有應用程序中注入此RestService bean,不僅是在SomeProxyImpl中(無論如何都無法正常工作)。 我怎樣才能做到這一點?
Spring不會自動連接新創建的字段,除非您這樣要求:ApplicationContextHolder.getContext()。getAutowireCapableBeanFactory()。autowireBean(object);
如果您的SomeProxyImpl類位於“ com.test.soapproxy”包中,並且您的類使用@Component進行注釋,則Spring必須已使用自動裝配的bean創建了一個實例。 然后,您應該從上下文中獲取此bean,並使用它而不是創建一個新bean。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.