Spring框架使用注解

首先要开启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 , 声明式事务仍需配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值