Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 855
Human Being Avatar asked Feb 16 '23 20:02

Human Being


2 Answers

ApplicationContext context=SpringApplication.run(YourProjectApplication.class, args);

this context can be used to get the beans created by annotation @Bean and @Service as

context.getBean(className.class);

like image 162
manoj jangam Avatar answered Feb 19 '23 09:02

manoj jangam


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.

like image 41
Donal Fellows Avatar answered Feb 19 '23 10:02

Donal Fellows