简体   繁体   中英

How to use Annotation initialize any class in Spring4?

This is old way i was using

<bean id="mybean" class="commodel.MyBean" init-method="init">
    <property name="userDao" ref="userModule"></property>
    <property name="myEmailid" value="${bean.email}"></property>         
</bean>

and in Java class i am using

MyBean myBean = (MyBean) SpringContextManager.getInstance().fetchBean("mybean");

But i am using latest Spring version how can use annotation to initialize the bean?

@Component("myBean")
public class MyBean {

  @Autowired 
  private UserDao userDao;

  @Value("${bean.email}")
  private String myEmailid;
}

You can remove the bean declaration in context.xml and add the following to enable auto-detect

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context                                 
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <context:component-scan base-package="commodel" /> 

</beans>

If you access MyBean from another bean, you can simply inject it using @Autowired.

If you access MyBean from POJO, you can get the instance through ApplicationContext.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM