不使用spring的xml配置,全权交给java来做
javaConfig是spring的一个子项目,在spring4之后,它成为了一个核心功能
实体类
package com.yl.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component//说明这个类被spring接管了,注入到了容器中
public class User {
private String name;
public String getName() {
return name;
}
@Value("yulu520")//属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置文件
package com.yl.config;
import com.yl.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;
@Configuration//这个也会被spring容器托管,注入到容器中,因为她本来也是一个@Component,
//@Configuration代表这是一个配置类,就和我们之前看的beans.xml
@ComponentScan("com.yl.pojo")
@Import(ylConfig2.class)
public class ylConfig {
@Bean
//注册一个bean,就相当于之前写得一个bean标签
//这个方法的名字,就相当于bean标签的id属性
//这个方法的返回值,就相当于bean标签中的class属性
public User getUser(){
return new User();
}
}
测试类
import com.yl.config.ylConfig;
import com.yl.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(ylConfig.class);
User getUser=(User) context.getBean("getUser");
System.out.println(getUser.getName());
}
}
结果
yulu520
这种纯java的配置方式,在SpringBoot中随处可见