- 简单实体类
package indi.stitch.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("Stitch")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
@Component注解将实体类交给Spring容器托管,成为一个SpringBean组件
- JavaConfig配置类
package indi.stitch.config;
import indi.stitch.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("indi.stitch.pojo")
public class BeanConfig {
@Bean
public User getUser() {
return new User();
}
}
@Configuration注解代表这个类为Bean的配置类,相当于xml配置文件,本质上也是一个Component
@ComponentScan注解限定了配置类的扫描范围
@Bean表示被注册的Bean,相当于xml配置文件中的bean标签
- 测试类
import indi.stitch.config.BeanConfig;
import indi.stitch.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.getName());
}
}
使用JavaConfig的方式实现配置,需要使用AnnotationConfigApplicationContext类通过传入配置类的字节码对象获取Spring配置上下文,在此上下文中可以获取被@Bean标签标记的Bean对象,传入的参数为被@Bean标签标记的方法的方法名。
- 测试结果