Spring Boot-04Spring Boot基础-使用注解装配bean
版权声明:【show me the code ,change the world】 https://blog.csdn.net/yangshangwei/article/details/83352400
文章目录
- 概述
- 示例
Spring Boot主要是通过注解来装配 Bean 到 Spring IoC 容器中,使用注解装配Bean就不得不提AnnotationConfigApp licationContext
,很显然它是一个基于注解的 IoC 容器。
之前的博文 Spring-基于Java类的配置
POJO类
package com.artisan.springbootmaster.pojo;
public class Artisan {
public String name;
public int age;
// setter/getter
}
然后编写一个配置文件
package com.artisan.springbootmaster;
import com.artisan.springbootmaster.pojo.Artisan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean(name = "artisan")
public Artisan initArtisan(){
Artisan artisan = new Artisan();
artisan.setName("小工匠");
artisan.setAge(20);
return artisan;
}
}
-
@Configuration
代表是一个 Java 配置文件 , Spring会根据它来生成 IoC 容器去装配 Bean @Bean
代表将 initArtisan方法返回的 POJO 装配到 IoC 容器中,属性 name 定义 Bean 的名称,如果没有配置它,则会将方法名称“initArtisan
作为 Bean 的名称保存到 Spring IoC 容器中 。
使用 AnnotationConfigApplicationContext 来构建
package com.artisan.springbootmaster;
import com.artisan.springbootmaster.pojo.Artisan;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class LoadTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
//Artisan artisan = applicationContext.getBean(Artisan.class);
Artisan artisan = (Artisan) applicationContext.getBean("artisan");
System.out.println(artisan.getName() + " || " + artisan.getAge());
}
}
-
new AnnotationConfigApplicationContext(AppConfig.class)
将 Java 配置文件 AppConfig 传递给 AnnotationConfigApplicationContext 的构造方法,这样它就能够实例化该配置类中定义的信息,然后将配置里面的 Bean 装配到 IoC 容器中 - 装载到IoC容器以后,就可以使用getBean来获取对应实例化的bean信息了
输出 :
23:08:36.164 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean "artisan"
小工匠 || 20
关键日志:Returning cached instance of singleton bean "artisan"
,可以知道配置在配置文件中 的名称为 artisan的 Bean 已经被装配到 IoC 容器中 ,并且可以通过 getBean方法获取对应的 Bean.
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。