- Spring学习笔记(一) - 注解开发(重点内容)
- 注解开发定义Bean
- 纯注解开发
- Bean作用范围 与 Bean生命周期
- 注解开发依赖注入
- 引用类型
- 简单类型
-
使用@Component定义bean
//在调用getBean时参数为bookService.class 不需要强制类型转换 @Component public class BookServiceImpl implements BookService { public void save() { System.out.println("book service save ..."); } } //在调用getBean时参数为"bookDao",需要强制类型转换 @Component("bookDao") public class BookDaoImpl implements BookDao { public void save() { System.out.println("book dao save ..."); } }
-
核心配置文件中通过组件扫描加载bean
-
Spring提供了@Component注解的三个衍生注解,格式同@Component
@Controller:用于表现层bean定义
@Service:用于业务层bean定义
@Repository:用于数据层bean定义
@Configuration注解用于设定当前类为配置类
@ConponentScan注解设定扫描路径,此注解只能添加一次,多个数据请用数组格式
- 通过Java类代替Spring核心配置文件
//@ComponentScan里面的参数可以通过添加{}选择扫描多个路径下的包 @Configuration @ComponentScan("com.itheima") public class SpringConfig { }
- 加载的方法
public class AppForAnnotion { public static void main(String[] args) { //加载配置类初始化容器 ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class); BookDao bookDao = (BookDao) ctx.getBean("bookDao"); bookDao.save(); } }
- 使用@Scope定义bean作用范围
- 使用@PostConstruct,@PreDestroy
@Component @Scope("singleton") public class BookServiceImpl implements BookService { public void save() { System.out.println("book service save ..."); } @PostConstruct public void init(){ System.out.println("init..."); } @PreDestroy public void destroy(){ System.out.println("destroy..."); } }
-
使用@Qualifier注解开启指定名称装配bean
public class BookServiceImpl implements BookService { //@Qualifier注解不能单独使用必须配合@Autowired注解使用 @Autowired @Qualifier("bookDao") private BookDao bookDao; }
-
注意:
自动装配基于反射设计创建对象并暴力反射对应属性为私有属性的私有化数据,因此无需提供setter方法;
自动装配建议使用无参构造方法对象(默认),如果不提供对应构造方法,请提供唯一的构造方法;
- 使用@value 实现简单类型注入 (注意:路径仅单一文件配置,多文件请使用数组格式配置,不允许使用通配符 *)
public class BookDaoImpl implements BookDao { @Value("mysql") private String connectionName; }
- 使用 @PropertySource 注解加载properties文件
@Component("bookDao") @PropertySource("jdbc.properties") public class BookDaoImpl implements BookDao { @Value("${name}") private String connectionName; public void save() { System.out.println("book dao save ..."+connectionName); } }