我们现在要完全不使用Sping的xml配置了, 全权交给Java来做!
JavaConfig是一个Spring的子项目, 在Spring4以后, 它成为了一个核心功能
1、实体类:
package com.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("身伤易逝")//注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + 'n' +
'}';
}
}
2、配置类(相当于之前的xml文件)
@Configuration_//相当于, 代表这是一个配置类
//这个也会被Spring托管, 注册到了容器中, 因为他本来就是一个@Component
@ComponentScan(“com.pojo”)//扫描包中的注解
@import(Config2.class)//引入其他配置类
_
**public class **MyConfig {
_//注册一个bean 相当于
//方法名就是id, 返回值就是class属性
@Bean
**public **User getUser() {
**return new **User();//就是返回要注入到bean的对象!
_}
}
package com.config; import com.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 @ComponentScan("com.pojo")//扫描包中的注解 @import(Config2.class)//引入其他配置类 public class MyConfig { //注册一个bean 相当于 //方法名就是id, 返回值就是class属性 @Bean public User getUser() { return new User();//就是返回要注入到bean的对象! } }
3、测试类
//如果完全使用了配置文件方式去做, 我们就只能通过 AnnotationConfig 上下文来获取容器, 通过配置类的class对象加载!
**new **AnnotationConfigApplicationContext(MyConfig.**class**);
import com.config.MyConfig;
import com.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
//去对象用方法名
User user = (User) context.getBean("getUser");
System.out.println(user.getName());
}
}
纯Java注解的配置方法, 在SpringBoot中随处可见



