参考链接
spring注解驱动一
spring注解驱动二
spring注解驱动三
spring注解驱动四
spring注解驱动五
spring注解驱动六
spring注解驱动视频
一、xml配置和注解配置
1.1 xml配置
1.1.1 结构
1.1.2 pom
4.0.0org.examplespring-annotation1.0-SNAPSHOTorg.springframeworkspring-context5.2.6.RELEASEorg.projectlomboklombok1.16.8junitjunit4.12test
1.1.3 业务类
@Getter
@Setter
@NoArgsConstructor
@ToString
@AllArgsConstructor
public class Person {
private String name;
private Integer age;
}
1.1.4 测试类
1.2 注解方式
1.2.1 配置类
配置类等同于以前的配置文件,只不过一个是java代码的形式,一个是xml配置的形式
package com.best.config;
import com.best.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//配置类==配置文件
@Configuration //告诉Spring这是一个配置类
public class MainConfig {
//给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
@Bean(name = "person1")
public Person person() {
return new Person("lisi", 20);
}
}
1.2.2 测试类
二、组件注册
2.1 @ComponentScan自动扫描组件
以前是在配置文件中写,component-scan,现在呢,配置类就相当于配置文件,我们只需要在配置类上加上@ComponentScan注解即可
2.1.1 基本用法
package com.best.controller;
import org.springframework.stereotype.Controller;
@Controller
public class BookController {
}
package com.best.dao;
import org.springframework.stereotype.Repository;
@Repository
public class BookDao {
}
package com.best.service;
import org.springframework.stereotype.Repository;
@Repository
public class BookService {
}
2.1.2 exludeFilters
2.1.3 includeFilters
2.1.4 FilterType.ASSIGNABLE_TYPE
2.2 @Scope设置组件作用域
2.2.1 配置类
package com.best.config;
import com.best.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class MainConfig2 {
/**
* 默认都是单实例的
* prototype: 多实例的, ioc容器启动并不会去调用方法创建对象放在容器中。每次获取的时候才会调用方法创建对象。
* singleton: 单实例的(默认值), ioc容器启动会调用方法创建对象放到ioc容器中。以后每次获取就直接从容器(map.get())中拿。
* request: 同一个请求创建一个实例
* session: 同一个session创建一个实例
* @return
*/
@Scope("prototype")
@Bean("person2")
public Person person() {
System.out.println("给容器中添加Person....");
return new Person("张三", 25);
}
}
2.2.2 scope配置
2.3 @Lazy-bean懒加载
2.4 @Conditional按照条件注册bean
2.5 @Import给容器中快速导入一个组件
2.5.1 @Import
2.5.2 @ImportSelector
gitee源码
