@Configuration注解
作用一:@Configuration配置spring 并 启动spring容器
spring容器配置类
@Configuration
public class SpringConfig {
public SpringConfig(){
System.err.println("SpringConfig启动");
}
}
主线程启动类
@SpringBootApplication
public class Demo2Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext(SpringConfig.class);
System.err.println("服务启动成功");
}
}
结果
可以看出我们在主程序里面启动了spring容器,@Configuration配置SpringConfig并启动Spring容器
作用二:@Configuration启动容器+@Bean注册Bean,@Bean下管理bean的生命周期
启动类
@SpringBootApplication
public class Demo2Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext(SpringConfig.class);
System.err.println("服务启动成功");
User getUser = annotationConfigApplicationContext.getBean("getUser", User.class);
System.err.println(getUser);
}
}
实体类
public class User {
@Value("yyb")
private String name;
@Value("nan")
private String sex;
@Value("15")
private Integer age;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
spring容器配置类 并在里面注册bean
@Configuration
@ComponentScan("com.yun.demo2.pojo")
public class SpringConfig {
public SpringConfig(){
System.err.println("SpringConfig启动");
}
@Bean
public User getUser(){
return new User();
}
}
结果
可以看出注册bean成功:用@Bean注解时方法名相当于 bean的id 返回值是bean的class
作用三:@Configuration启动容器+@Component注册Bean
启动类
@SpringBootApplication
public class Demo2Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext(SpringConfig.class);
System.err.println("服务启动成功");
User getUser = annotationConfigApplicationContext.getBean("user", User.class);
System.err.println(getUser);
}
}
实体类并用@component注册bean
@Component
public class User {
@Value("yyb")
private String name;
@Value("nan")
private String sex;
@Value("15")
private Integer age;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
spring配置类
@Configuration
@ComponentScan("com.yun.demo2.pojo")
public class SpringConfig {
public SpringConfig(){
System.err.println("SpringConfig启动");
}
}
结果
可以看出注册bean成功,当使用@component注解时,类名小写相当于bean的id 同时类名也表示实体类名 所有类名也是bean的class