![](/img/trans.png)
[英]Could private static class Spring bean annotated @Service be autowired?
[英]Get bean of @Service annotated class?
在我的Web应用程序中,我没有使用applicationContext.xml
。 如何获取@Service
注释类的bean?
如果我在我的Web应用applicationContext.xml
中使用了applicationContext.xml
,则每次都必须加载applicationContext.xml
以获取@Service
注释类的bean。
我用这种方式
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext);
ServerConnection con = (ServerConnection ) ctx.getBean("con");
我的服务类将是,
@Service or @Service("con")
public class ServerConnection {
private TServerProtocol tServerProtocol;
private URI uri;
public TServerProtocol getServerConnection(){
System.out.println("host :"+host+"\nport :"+port);
try {
uri = new URI("tcp://" + host + ":" + port);
} catch (URISyntaxException e) {
System.out.println("Exception in xreating URI Path");
}
tServerProtocol = new TServerProtocol(new Endpoint(uri));
return tServerProtocol;
}
}
有没有其他方法来获得这个类的bean ?
要么
在Spring3.x中核心应用程序和Web应用程序的情况下,获取@Service
注释类的bean的正确方法是什么?
ApplicationContext context=SpringApplication.run(YourProjectApplication.class, args);
此上下文可用于获取注释@Bean
和@Service
创建的bean
context.getBean(className.class);
如果使用基于注释的配置,则使用@Autowired
按类型获取bean,或使用@Resource
以获取bean的名称。 对于任何特定属性,只使用其中一个(以避免混淆)。
@Autowired
private ServerConnection connection;
@Resource(name = "con")
private ServerConnection connection;
还有@Inject
,但我不喜欢它,因为随着bean数量的增加,它变得不那么好了。 因人而异。
由于您正在使用注释,我相信您更愿意使用@Autowired 。 如果你有一个将调用ServerConnection
的类(比如com.foo
包下的CallingClass
),那么它就是这样的:
package com.foo;
@Component
public class CallingClass{
@Autowired
private ServerConnection serverConnection
// add your getters and setters
}
然后在applicationContext.xml上添加以下内容
<context:component-scan base-package="com.foo" />
希望我回答你的问题。
如果您在spring之外的某个bean中工作,那么您可以使用普通的Spring注释:
@Autowired
private Dependency1 dependency1;
@Autowired
private Dependency2 dependency2;
@Autowired
private Dependency2 dependency2;
然后从这个类的内部调用一次:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
注入所有依赖项。 如果您有多个依赖项,可能会更方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.