Get bean of @Service annotated class?
Solution 1
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.
Solution 2
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);
Human Being
Always willing to learn the new things to enhance my knowledge .
Updated on June 04, 2022Comments
-
Human Being almost 2 years
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 theapplicationContext.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?