Human Being Human Being - 3 months ago 8
Java Question

Get bean of @Service annotated class?

In my web application, I am not using

applicationContext.xml
. How can I get the bean of
@Service
annotated class?

If I used the
applicationContext.xml
in my web application, I have to load the
applicationContext.xml
every time to get the bean of the
@Service
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 ?

or

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

Answer

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).

@Autowired
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.