Spring常用注解说明

1、DAO层(存储层)要用@Repository注解,Service层(业务层)用@Service,Control层(展示层)用@Controller

2、@Autowired注释。

引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。不需要再生成set和get方法。

@Service("studentService")
@Transactional
public class StudentServiceImpl implements StudentService{
	@Autowired
	private StudentDAO studentDao;
}
@Service("studentService")
@Transactional
public class StudentServiceImpl implements StudentService{
	private StudentDAO studentDao;
	@Autowired
	public void setStudentDao(StudentDAO studentDao) {
		this.studentDao = studentDao;
	}
}

3、@Qualifier 
@Autowired是根据类型进行自动装配的。在上面的例子中,如果当Spring上下文中存在不止一个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。 Spring会找到id为userDao的bean进行装配。 

@Autowired  
public void setUserDao(@Qualifier("userDao") UserDao userDao) {   
    this.userDao = userDao;   
}  

4、@Resource

@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按byName自动注入罢了。@Resource有两个属性是比较重要的,分别是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。 

5、@PostConstruct(JSR-250) 
在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行(注:Bean初始化包括,实例化Bean,并装配Bean的属性(依赖注入))。 
它的一个典型的应用场景是,当你需要往Bean里注入一个其父类中定义的属性,而你又无法复写父类的属性或属性的setter方法时,如

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {   
    private SessionFactory mySessionFacotry;   
    @Resource  
    public void setMySessionFacotry(SessionFactory sessionFacotry) {   
        this.mySessionFacotry = sessionFacotry;   
    }   
    @PostConstruct  
    public void injectSessionFactory() {   
        super.setSessionFactory(mySessionFacotry);   
    }   
    ...   
}  

6、 使用<context:annotation-config />简化配置 

7、 使用<context:component-scan />让Bean定义注解工作起来

8、使用@Scope来定义Bean的作用范围 

@Scope("session")   
@Component()   
public class UserSessionBean implements Serializable {   
    ...   
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值