Spring学习笔记(二)
3. Annotation的用法
- applicationContext.xml里必须加入:
<context:annotation-config />
- @Autowired注解
默认按:byType找,如果该type配了多个bean,则在这些bean中再通过byName(变量名)的方式匹配,如还未找到或找到2个及以上则抛异常。
applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:annotation-config /> <context:component-scan base-package="com.wangj.spring" /> <bean id="userDao" class="com.wangj.spring.dao.impl.UserDaoImpl"> </bean> <bean id="u" class="com.wangj.spring.dao.impl.UserDaoImpl"> </bean> <bean id="userService" class="com.wangj.spring.service.UserService"> </bean> </beans>
UserService
public class UserService { @Autowired private UserDao userDao; public void add(User user) { userDao.save(user); } public void init(){ System.out.println("init"); } }
- @Qualifier("ud")注解
配合@Autowired注解使用,当想通过byName注入使用该注解
public class UserService { @Autowired @Qualifier("ud") private UserDao userDao; public void add(User user) { userDao.save(user); } public void init(){ System.out.println("init"); } }
- @Resource注解
按名称查找,可以指定名称如不指定按变量名
@Resource(name="userDao") private UserDao userDao;
- @Component @Service @Controller @Repository注解
使用这些注解,即可不在applicationContext.xml里配置bean,但xml里必须配上<context:component-scan base-package="com.wangj.spring" /> spring就会自己查找加入以上注解的类并初始化。
使用方法:默认名称为类名首字母小写(不是接口名首字母小写)
@Component public class UserDaoImpl implements UserDao {
指定名称:
@Component("userDao") public class UserDaoImpl implements UserDao {
- @Scope
使用方法:
@Scope("prototype") @Component public class UserDaoImpl implements UserDao { @Override public void save(User user) { System.out.println(String.format("user(%s) saved!", user.getUsername())); } }
- @PostConstruct
应用在方法上,类构造完成之后调用,相当于xml配置里的init-method
- @PreDestroy
应用在方法上,对象销毁之前调用,相当于xml配置里的destroy-method