注解开发Bean作用范围与管理既然我们的Bean开发从xml转移到注解开发 , 那么一些配置设置同样发生改变
首先我们介绍Scope范围的设置方式:
- @Scope:定义bean的作用范围
package com.itheima.dao.impl;import com.itheima.dao.BookDao;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Repository;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;@Repository//@Scope设置bean的作用范围(singleton或prototype) , 可以不添加默认singleton@Scope("singleton")public class BookDaoImpl implements BookDao {public void save() {System.out.println("book dao save ...");}}然后我们介绍一下bean生命周期的init和destroy操作:- @PostConstruct:定义init操作 , 表示构造后操作
- @PreDestroy:定义destroy操作 , 表示销毁前操作
- 使用@Autowired注解开启自动装配模式(按类型)
- 当存在相同类型时 , 我们采用@Qualifier开启按名自动装配
package com.itheima.service.impl;import com.itheima.dao.BookDao;import com.itheima.service.BookService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;@Servicepublic class BookServiceImpl implements BookService {//@Autowired:注入引用类型 , 自动装配模式 , 默认按类型装配@Autowired//@Qualifier:自动装配bean时按bean名称装配@Qualifier("bookDao")private BookDao bookDao;public void save() {System.out.println("book service save ...");bookDao.save();}}注意:自动装配基于反射设计创建对象并暴力反射对应属性为私有属性初始化数据 , 因此无需提供setter方法除了上述的bean类型装配 , 我们的简单类型装配依旧存在:
注意:自动转配建议使用无参构造方法创建对象(默认) , 如果不提供对应构造方法 , 请提供唯一的构造方法
注意:@Qualifier是基于@Autowired实现的 , 必须保证先有Autowired才能存在Qualifier
- 我们采用@Value的形式来配置简单类型的值
package com.itheima.dao.impl;import com.itheima.dao.BookDao;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Repository;@Repository("bookDao")public class BookDaoImpl implements BookDao {//@Value:注入简单类型(无需提供set方法)@Value("123")private String name;public void save() {System.out.println("book dao save ..." + name);}}之所以使用@Value的形式配置 , 是因为我们的类型值不一定是由手动输入的 , 有可能来自于Properties资源:- 首先我们需要在Springconfig中配置相关资源
package com.itheima.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;@Configuration@ComponentScan("com.itheima")//@PropertySource加载properties配置文件@PropertySource({"jdbc.properties"})public class SpringConfig {}- 然后我们在数据层调用时 , 采用${}来匹配数据
package com.itheima.dao.impl;import com.itheima.dao.BookDao;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Repository;@Repository("bookDao")public class BookDaoImpl implements BookDao {//@Value:注入简单类型(无需提供set方法)@Value("${name}")private String name;public void save() {System.out.println("book dao save ..." + name);}}
经验总结扩展阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 手机指南针怎么看(指南针怎么看方向)
- 指南针怎么看方向(指南针罗盘)
- 指南针怎么看东南西北(指南针怎么看家里方位)
- 星姿妍彩妆是什么牌子的彩妆?
- 飞甩鸡毛是什么牌子?
- 爱琪梅花是什么电视剧中的人物?
- 晒斑和黄褐斑的区别是什么?
- 父母爱情安泰结局是什么?
- 晒黑了怎么快速变白?
- 飞乔是什么牌子?
