@Component(“”)[email protected](name=””)的使用:
spring的配置文件配置:
<?xml version=“1.0” encoding=“UTF-8”?>
<beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xmlns:context=“http://www.springframework.org/schema/context”
xmlns:aop=“http://www.springframework.org/schema/aop”
xmlns:tx=“http://www.springframework.org/schema/tx”
xsi:schemaLocation=“http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd”>
<!– 扫描com.test 包,[email protected]/@Component等–>
<context:component-scan base-package=“com.test” />
<beans>
配置<context:component-scan base-package=”com.test” />解析:
使用ClassPathXmlApplicationContext(“bean.xml”)初始化bean.xml的时候,或者说初始化spring配置文件的时候,会自动扫描com.test下的所有包,[email protected],则将该类初始化为一个对象,[email protected](“name”)中指明的name,若不指明,则默认为类的名字首字母小写;当调用ctx.getBean(“userService”),时,则查看容器是否有一个名字为userService;如有则在初始化这个类得过程中,[email protected](name=”u”);则查看容器是否有名字叫u的bean,若有则将u注入到方法参数中,而后参数就会传人方法内,当然也就注入了成员变量里:
UserService.java文件中使用:
@Component(“userService”)
public class UserService {
private UserDAO userDAO = new UserDAOImpl();
private UserLogDAO userLogDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public UserLogDAO getUserLogDAO() {
return userLogDAO;
}
@Resource(name=“ulog”)
public void setUserLogDAO(UserLogDAO userLogDAO) {
this.userLogDAO = userLogDAO;
}
@Resource(name=“u”)
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
UserDAOImpl.java中使用:
@Component(“u”)
public class UserDAOImpl implements UserDAO {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void save(User u) {
Session s=sessionFactory.openSession();//.getCurrentSession();
//s.beginTransaction();
s.save(u);
System.out.println(“a user save,XXXX!”);
}
}
[email protected]@resource注解,相当于spring使用了如下的配置:
这样就可以省去之前在bean中所写的:
<!–
<bean id=“u” class=“com.test.dao.impl.UserDAOImpl”>
</bean>
<bean id=”UserService” class=”com.test.service.UserService”>
<property name=”UserDAO” ref=”u” />
</bean>
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/11241.html