Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaConfigSpring使bean对所有应用程序都可用_Java_Spring - Fatal编程技术网

JavaConfigSpring使bean对所有应用程序都可用

JavaConfigSpring使bean对所有应用程序都可用,java,spring,Java,Spring,我有一个带有main方法的jar。我创建了一个带有@Configuration注释的java配置 @Configuration @ComponentScan(basePackages = { "com.test.commons" }) public class ProxyConfig { } 在这个com.test.commons中,我放置了一个服务 package com.test.commons; @Service public class RestService { //d

我有一个带有main方法的jar。我创建了一个带有@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吗?)


我希望能够通过@Autowired在我的所有应用程序中注入这个restservicebean,而不仅仅是在SomeProxyImpl中(它无论如何都不起作用)。我该怎么做呢?

除非您要求,否则Spring不会自动关联由新创建的字段,如下所示:ApplicationContextHolder.getContext().getAutowireCapableBeanFactory().autowireBean(对象)

如果您的SomeProxyImpl类在“com.test.soapproxy”包中,并且您的类用@Component注释,那么Spring一定已经用自动连接的bean创建了一个实例。
然后,您应该从您的上下文中获取这个bean并使用它,而不是创建一个新的bean。

您是否使用了scanBasePackages:@SpringBootApplication(scanBasePackages={..}在控制器中自动连接您的
RestService
。这将满足您的需要。@melihcoskun我刚刚完成了。自动连接没有成功注入我的bean。您需要
@Autowire
某些代理,不要在其上使用
new
。您可以直接在主类中自动连接。然后将
端点.publish
方法放在另一个类中r方法(不在main中),放在一个用
@PostConstruct
ApplicationContextHolder注释的方法中,它不是spring jars中包含的一个类?嗯,很抱歉,它是我们内部框架中的一个类……但它只是一个实现“ApplicationContextAware”的类,可以轻松地为我们提供spring ApplicationContext。
@Component
public class SomeProxyImpl implements SomeServiceSoap {
@Autowired  RestService restService;