简体   繁体   English

如何在 Spring4 中使用 Annotation 初始化任何类?

[英]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在 Java 类中我正在使用

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

But i am using latest Spring version how can use annotation to initialize the bean?但是我使用的是最新的 Spring 版本,如何使用注释来初始化 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您可以删除 context.xml 中的 bean 声明并添加以下内容以启用自动检测

<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.如果你从另一个 bean 访问 MyBean,你可以简单地使用 @Autowired 注入它。

If you access MyBean from POJO, you can get the instance through ApplicationContext.如果从 POJO 访问 MyBean,则可以通过 ApplicationContext 获取实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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