0%

9.使用Java的方式配置Spring

9.使用Java的方式配置Spring

我们现在要完全不适应Spring的xml配置了,全权交给Java来做

JavaConfig是Spring的一个子项目,在Spring4之后成为了一个核心功能

实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.lwj.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这里这个注解的意思就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
@Value("张三")
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}

配置类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.lwj.config;

import com.lwj.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //这个也会被Spring接管,注册到容器中,因为他本来也是一个Component,
// Configuration代表这是一个配置类,就和我们之前看的xml是一样的
@ComponentScan("com.lwj")
public class MyConfig {

//注册一个Bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean的id
//返回值就相当于bean标签的class
@Bean
public User getUser(){
return new User();//返回要注入到bean的对象
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.lwj.config.MyConfig;
import com.lwj.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {


@org.junit.Test
public void test1(){
//如果完全无使用了配置类去做,
// 我们就只能通过AnnotationConfigApplicationContext 上下文获取容器
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = (User) context.getBean("getUser");
System.out.println(user.getName());
}
}

这种Java配置方式,在Spring Boot中随处可见!