Spring新手学习----注解

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值