Human Being Human Being - 2 months ago 5x
Java Question

Get bean of @Service annotated class?

In my web application, I am not using

. How can I get the bean of
annotated class?

If I used the
in my web application, I have to load the
every time to get the bean of the
annotated class.

I used this way

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext);
ServerConnection con = (ServerConnection ) ctx.getBean("con");

My Service class will be as ,

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

Is there any other way to get a bean of this class ?


What is the proper way to get a bean of
annotated class in case of core application and web application in Spring3.x?


If you are using annotation-based configuration, you use @Autowired to get the bean by its type or @Resource to get the bean by its name. Use only one of these for any particular property (to keep confusion down).

private ServerConnection connection;
@Resource(name = "con")
private ServerConnection connection;

There's also @Inject, but I don't like that as it gets less nice as the number of beans goes up. YMMV.