使用Java的方式配置Spring
我们现在要完全不适用Spring的xml配置了,全权交给java来做!
JavaConfig是Spring的一个子项目,在Spring4之后,它变成了核心功能
配置类:
package com.vekzjj.config;
import com.vekzjj.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//这个也会被Spring容器托管,注册到容器中,他本是就是一个@Component
//@Configuration代表这是一个配置类,和beans.xml一样
@Configuration
@ComponentScan("com.vekzjj.pojo")
public class Myconfig {
//注册一个bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入到bean的对象
}
}
package com.vekzjj.pojo;
import org.springframework.beans.factory.annotation.Value;
public class User {
private String name;
public String getName() {
return name;
}
@Value("vekzjj")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
测试类:
public class DemoTest {
public static void main(String[] args) {
//荣光完全使用了配置类方法去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(Myconfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.getName());
}
}