9. JavaConfig 配置
我們現在要完全不使用Spring的xml配置了,全權交給lava來做
JavaConfig 是 Spring 的一個子項目,在 Spring 4 之后,它成為了一個核心功能!
User.java 實體類
package com.peng.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//這里這個注解的意思,就是說明這個類被Spring注冊到了齊器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("peng") //屬性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
MyConfig.java 配置類
package com.peng.config;
import com.peng.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//這個也會Spring容器托管,注冊到容器中。因為他本來就是一個@Component
@Configuration //@Configuration代表這是一個配置類,跟beans.xml一樣
@ComponentScan("com.peng")
@Import(MyConfig2.class) //合並其他beans配置
public class MyConfig {
//注冊一個bean,就相當於我們之前寫的bean標簽
//方法名:bean標簽中的id
//返回值:bean標簽中的class
@Bean
public User getUser(){
return new User(); //就是返回要注入bean的對象!
}
}
MyTest.java 測試類
import com.peng.config.MyConfig;
import com.peng.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
//如果完全使用了配置類方式去做,我們就只能通過AnnotationConfig上下文來獲取容器,通過配置類的class對象加載!
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("user",User.class);
System.out.println(user.getName());
}
}
這種純Java的配置方式,在SpringBoot中隨處可見!
