首先要开启context命名空间
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
开启注解解析,其中base-package为注解类所在的包,多个包之间可用,
隔开
<context:component-scan base-package="cn.action,cn.dao,cn.service"></context:component-scan>
Spring常用的 注解 :
@Component
: 标注在 类上, 该类 将被解析为一个bean ,无需再 配置该类的
该注解为通用注解 ,可注解Action类, 业务层类, Dao层类 ,
@Controller
: 标注在 Action类/springMVC的Controller类上 , 专用注解 , 相比 @Component,职责更单一, 可读性更高
@Service
: 标注在业务层类上
@Repository
: 标注在 DAO层类上
@Component
,@Controller
,@Service
,@Repository
都可通过在其后加(“名字”)设值,相当于中的id
如@Component("loginService")
相当于 <bean id="loginService">
@Autowired
: 标注在 类的属性或 set方法上 , 自动装配 注入
默认安装 byType自动装配
如果希望通过 byName自动装配,需要结合 注解 @Qualifier(“bean的id”)
@Resource
: 功能类似于 @Autowired
不通之处在于, @Autowired 默认 byType自动装配 ; @Resource 默认 byName自动装配
@Resource(name="所依赖的bean的id")
; @Resource(type=接口.class) 通过指定所依赖的bean的接口类型, 通过byType进行自动装配
``使用注解后仍需要在Spring的xml中配置sessionFactory , dataSource的 bean , 声明式事务仍需配置