9、使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了,全权交给java来做!
JavaConfig 是Spring的一个子项目,在Spring4之后,它成为了一个核心功能
pojo
package com.chif.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
@Value("chif")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置类
package com.chif;
import com.chif.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
//@Configuration代表是一个配置类,代替之前的beans.xml
//这个类也会被Spring容器托管,注册到容器中,因为它本来就是一个@Commponent
@ComponentScan("com.chif.pojo")
public class MyConfig {
//注册一个bean,就相当于之前的一个bean标签
//这个方法的名字相当于bean标签中的id
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();
}
}
测试
import com.chif.MyConfig;
import com.chif.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class myTest {
@Test
public void test(){
//如果完全使用了配置类的方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User getUser = (User) context.getBean("getUser");
System.out.println(getUser.getName());
}
}
这种纯java的配置方式,在SpringBoot中随处可见!