全注解下的Spring IoC

IoC(控制反转)是一种通过描述来生成或者获取对象的技术。

一、配置文件装配Bean到IoC容器

1、定义一个简单的Java对象

1
2
3
4
5
6
7
@Setter
@Getter
public class User {
private Long id;
private String userName;
private String note;
}

2、定义Java配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
//代表这是一个Java配置文件
@Configuration
public class AppConfig {
//代表方法返回的对象会装配到IoC容器,name属性返回bean的名称,否则名称为方法的小写
@Bean(name = "user")
public User initUser() {
User user = new User();
user.setId(1L);
user.setUserName("user_name");
user.setNote("note_1");
return user;
}
}

3、构建容器并测试

1
2
3
4
5
6
7
8
9
10
11
12
public class IoCTest {

private static Logger log = LoggerFactory.getLogger(IoCTest.class);

public static void main(String[] args) {
//将配置文件传递给AnnotationConfigApplicationContext的构造方法
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
User user = ctx.getBean(User.class);
log.info("{}",user.getId());
log.info("{}",user.getUserName());
}
}

4、控制台输出结果:

1
11:14:52.543 [main] INFO com.szy.springboot.config.IoCTest - user_name

二、配置文件装配Bean到IoC容器

1、类加入注解@Component

1
2
3
4
5
6
7
8
9
10
//标明类会被扫描
@Component
@Setter
@Getter
public class Dog {
@Value("dog_name")
private String name;
@Value("18")
private int age;
}

2、配置文件加入注解@ComponentScan

1
2
3
4
@Configuration
@ComponentScan(basePackages ="com.szy.springboot.entity")
public class AppConfig {
}

3、测试扫描

1
2
3
4
5
6
7
8
9
10
11
12
public class IoCTest {

private static Logger log = LoggerFactory.getLogger(IoCTest.class);

public static void main(String[] args) {
//将配置文件传递给AnnotationConfigApplicationContext的构造方法
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
//getBean方法获取对应的对象
Dog dog=ctx.getBean(Dog.class);
log.info("{}",dog.getName());
}
}

4、控制台输出结果:

1
11:14:52.545 [main] INFO com.szy.springboot.config.IoCTest - dog_name

三、依赖注入

1、定义接口

1
2
3
4
5
public interface Person {
public void service();

public void setAnimals(Animal animals);
}
1
2
3
public interface Animal {
public void use();
}

2、实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component
public class BussinessPerson implements Person {
//根据属性类型(byType)找到对应的bean注入
@Autowired
//消除歧义
@Qualifier("parrot")
private Animal animal = null;

@Override
public void service() {
this.animal.use();
}

@Override
public void setAnimals(Animal animal) {
this.animal = animal;
}
}
1
2
3
4
5
6
7
8
9
@Component
//设置优先级
@Primary
public class Parrot implements Animal {
@Override
public void use() {
System.out.println("鹦鹉叫");
}
}

3、IoC容器

1
2
3
4
5
6
7
8
9
10
11
12
public class IoCTest {

private static Logger log = LoggerFactory.getLogger(IoCTest.class);

public static void main(String[] args) {
//将配置文件传递给AnnotationConfigApplicationContext的构造方法
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
//getBean方法获取对应的对象
Person person=ctx.getBean(BussinessPerson.class);
person.service();
}
}

4、控制台输出

1
鹦鹉叫