这是我以前使用的旧方法
<bean id="mybean" class="commodel.MyBean" init-method="init">
<property name="userDao" ref="userModule"></property>
<property name="myEmailid" value="${bean.email}"></property>
</bean>
在Java类中,我正在使用
MyBean myBean = (MyBean) SpringContextManager.getInstance().fetchBean("mybean");
但是我正在使用最新的Spring版本,如何使用注释来初始化bean?
@Component("myBean")
public class MyBean {
@Autowired
private UserDao userDao;
@Value("${bean.email}")
private String myEmailid;
}
您可以在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>
如果从另一个bean访问MyBean,则可以简单地使用@Autowired注入它。
如果从POJO访问MyBean,则可以通过ApplicationContext获取实例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句