一、Spring中使用注解实现Bean的定义
在dao的实现类中添加数据访问层的注解Bean,代码例下:
package com.jbit.ssh.dao.impl; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import com.jbit.ssh.dao.DeptDao; import com.jbit.ssh.entity.Dept; @Component("deptDao") //用于标注dao类 public class DeptDaoImpl implements DeptDao { public List<Dept> getAll() { //List<Dept> list=sessionFactory.openSession().createQuery("from Dept").list() ; /* * getHibernateTemplate()是用来得到HibernateTemplate的方法,HiernateTemplate中提供了一系列的对数据库操作方法 * find 查询 参数是hql语句 * save 增加 * update 更新 * delete 删除 */ List<Dept> list=getHibernateTemplate().find("from Dept"); System.out.println("*****数据库操作得到所有的部门信息*******"); return list; } }
以上标红的注解代码和在spring配置文件中定义<bean id="deptDao" class="com.jbit.ssh.dao.imp.DeptDaoImpl"/>效果是一样的,除了@Component,Spring还提供了3个特殊的注解:
@Repository:用于标注Dao层的类。
@Service:用于标注业务层类。
@Controller:用于标准控制器的类。
使用注解配置信息需要在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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" > <!-- 扫描包中注解注释的类 --> <context:component-scan base-package="com.jbit.ssh.dao,com.jbit.ssh.service"> </context:component-scan> </beans>
以上代码中,首先添加对context命名空间的声明,然后使用context命名空间下的component-scan扫描注解标注的类,
base-paceage属性指定了要扫描的基本包,spring会扫描这个包里面的所有的类,获取Bean的定义信息。
二、在spring中使用注解实现自动装配
在业务处理类的属性上添加@Autowire 或者在方法的参数进行标注。
package com.jbit.ssh.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.jbit.ssh.dao.DeptDao; import com.jbit.ssh.entity.Dept; import com.jbit.ssh.service.DeptService; //@Service("deptService") //用于标准service类 public class DeptServiceImpl implements DeptService { @Autowired //自动按类型装配 @Scop(session) //指定作用域 private DeptDao deptDao; //这没有自动装配 public void setDeptDao(DeptDao deptDao) { this.deptDao = deptDao; } public List<Dept> getAll() { System.out.println("service层的方法getAll()"); List<Dept> list=deptDao.getAll(); return list; } public DeptServiceImpl(DeptDao deptDao) { super(); this.deptDao = deptDao; } public DeptServiceImpl() { super(); } }
时间: 2024-08-30 09:19:47