使用Java的方式配置spring
使用Java的方式配置spring
- 我们现在要完全不适用spring的xml配置了,全权交给java来做!
- JavaConfig是Spring的一个子项目,在spring4之后,它成为了一个核心的功能!
实体类:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @description:
* @auther lurongrong
* @create 2021-06-06 15:30
*
*/
//这里这个注解的意思,就是说明这个类被spring接管了,注册到了容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("赵丽颖")//属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置文件:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import pri.rong.pojo.User;
/**
* @description:
* @auther lurongrong
* @create 2021-06-06 15:33
*/
//这个也会被spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,就和我们之前看到的beans.xml
@Configuration
@ComponentScan("pri.rong.pojo")
@Import(Config2.class)
public class Config1 {
//注册一个bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入的bean对象
}
}
测试类:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import pri.rong.config.Config1;
import pri.rong.pojo.User;
/**
* @description:
* @auther lurongrong
* @create 2021-06-06 15:37
*/
public class MyTest {
public static void main(String[] args) {
//如果完全使用了配置类的方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(Config1.class);
User getUser = (User) context.getBean("user");
System.out.println(getUser.getName());
}
}
这种纯java的配置方式,在springBoot中随处可见!!!