Spring-注解

目录

 

1.声明bean

2 注入(DI)

3.注解所需配置


1.声明bean

用于替换自建类型组件的 <bean...>标签;可以更快速的声明bean

@Service  业务类专用

@Repository   dao实现类专用

@Controller    web层专用

@Component   通用

@Scope     用户控制bean的创建模式

// @Service说明 此类是一个业务类,需要将此类纳入工厂  等价替换掉 <bean class="xxx.UserServiceImpl">
// @Service默认beanId == 首字母小写的类名"userServiceImpl"
// @Service("userService") 自定义beanId为"userService"
@Service //声明bean,且id="userServiceImpl"
@Scope("singleton") //声明创建模式,默认为单例模式 ;@Scope("prototype")即可设置为多例模式
public class UserServiceImpl implements UserService {
 	...   
}
/* <bean id="empServices" class="com.cos.services.impl.EmpServicesImpl" autowired="byType"></bean> */
// 不写的时候默认为类名首字母小写,也可以写上指定的bean Name
@Service("empService")
//@Repository("empService")
//@Component("empService")   应用在组件的注解,赋值对象的创建,第三方软件/组建功能
@Scope("singleton")
public class EmpServiceImpl implements EmpService {...}

2 注入(DI)

用于完成bean中属性值的注入

@Autowired   基于类型自动注入(byType)

@Resource    基于名称自动注入(byName)

@Qualifier("userDao")限定要自动注入的bean的id,一般和@Autowired联用

@Value注入简单类型数据

public class EmpServiceImpl implements EmpService {
    /**
     * @author: qiuyongqi
     * @time: 15:37 2021/5/18
     * @description: spring提供的注解 @Autowired 默认使用数据类型(byType)进行注入,如果出现2个相同类型,就自动切换使用beanName注入,
     *                       如果加入@Qualifier("empMapper"),代表使用beanName来进行注入名称是 empMapper
     *              j2ee提供的注解 @Resource 默认beanName找注入,如果BeanName没有找到就自动切换找数据类型相同的注入
     *              他可以设置2个属性分别是name使用beanName注入(name = "empMapper",),type使用数据类型注入(type = EmpDao.class)
     *              2个属性可以同时使用
     */
//    @Autowired
//    @Qualifier("empDao")
    @Resource(name = "empDao",type = EmpDao.class)
    private EmpDao empDao;

//...
}

3.注解所需配置

<!-- 告知spring,哪些包中 有被注解的类、方法、属性 -->
<!-- <context:component-scan base-package="com.qf.a,com.xx.b"></context:component-scan> -->
<!-- 加载注解扫描 -->
<context:component-scan base-package="com.qf"></context:component-scan>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值