【Spring Framework】9、使用Java配置Spring
使用Java的方式配置Spring
完全不使用spring的xml配置,全交给Java来实现!
JavaConfig 是Spring 的一个子项目,在Spring4 之后,成为了一个核心功能!
User实体类
package com.xg.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
// 这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
@Value("遇见星光")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置类
MyConfig
package com.xg.config;
import com.xg.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 一样
@Configuration
@ComponentScan("com.xg")
@Import({MyConfig2.class})
public class MyConfig {
// 注册一个bean ,相当于bean标签,
// 这个方法的名字就相当于 标签中的 id
@Bean
public User getUser() {
return new User();
}
}
MyConfig2
package com.xg.config;
import com.xg.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.xg")
public class MyConfig2 {
@Bean
public User user2() {
return new User();
}
}
测试类
import com.xg.config.MyConfig;
import com.xg.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
@Test
public void test1(){
// 如果完全使用了配置类方式,就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的clas对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.toString());
}
}