Spring(三)——注解方式(Annotation)

一.注入对象/属性

定义在变量(不推荐,破坏封装性)或setter上
首先在beans之间添加<context:annotation-config/>
@Autowired 生成Bean时会自动在容器里根据类型匹配

@Autowired
public void setCategory(Category category) {
    this.category = category;
}

@Resource(推荐) 可以注入指定name的bean。默认按名称,找不到名称按类型匹配

@Resource(name="c")
private Category category; 

二.对Bean的注解(扫描组件)

先新增<context:component-scan base-package=”包名”/>
让容器自己去包里扫描,不需要再手动配置<bean></bean>
在源码的类增加@Component注解,即表明此类是bean,扫描到以后容器就生成一个bean

@Component("p")
public class Product {

另外,因为配置从applicationContext.xml中移出来了,所以属性初始化放在属性声明上进行。
常用注解:
@Compenent 通用注解

@Repository 持久层组件注解

@Service 业务层组件注解

@Controller 控制层组件处理

@Value 可以注入指定变量的值

@Scope 可以指定对象的作用域singleton(单例模式,默认)、prototype(多例模式)、request、session、global Session,

@Transactional 表示事务

    原文作者:Myosotis
    原文地址: https://segmentfault.com/a/1190000013316811
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞