Spring新手学习–注解
注解的优势:减少Spring-context.xml的配置(实际为减少<bean>
的配置)
劣势:注解内容与源代码紧密耦合
Spring常用注解
- @Component:标记在类上,该类将被解析为一个
<bean>
,该注解为通用注解,可以注解在Action类,业务层类,Dao层类 - @Controller:标记在Action类上,比@Component职责更单一,可读性高
import org.springframework.stereotype.Controller;
@Controller("userAction")
public class UserLogin {
public String userlogin(){
return "success";
}
}
- @Service标记在业务层类上
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.yunhe.biz.EmpBiz;
import cn.yunhe.dao.EmpDao;
import cn.yunhe.entity.Emp;
@Service("empBiz")
public class EmpBizImpl implements EmpBiz {
@Autowired
private EmpDao empDao;
@Override
public int addEmp(Emp emp) {
return empDao.add(emp);
}
public EmpDao getEmpDao() {
return empDao;
}
public void setEmpDao(EmpDao empDao) {
this.empDao = empDao;
}
}
- @Respository:标记在Dao层类上
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cn.yunhe.dao.EmpDao;
import cn.yunhe.entity.Emp;
@Repository("empDao")
public class EmpDaoImpl implements EmpDao {
@Autowired
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
@Override
public List<Emp> findEmps() {
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Emp where empno>=?");
query.setInteger(0, 7788);
List<Emp> emps = query.list();
return emps;
}
- @Autowired:标记在类的属性或Set()方法上,自动装配注入,默认自动装配类型为bytype,如需改变需加@Qualifier(bean的“id”)
- @Resource:功能类似于@Autowired,不同之处是@Autowired默认byType自动装配,@Resource默认byName自动装配
开启注解
在Spring-Context.xml文件中配置
<context:component-scan base-package="cn.yunhe.action,cn.yunhe.biz,cn.yunhe.dao,"></context:component-scan>