【SpringBoot基础】@Bean实例相关配置

【SpringBoot基础】@Bean实例相关配置

内容概要

实例说明如何通过注解,创建单例、“多例”,调用不同配置下 同名实例的方法。

环境Jar包

jdk: jdk1.8.0_121(32位)
pom:
	 <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.10.RELEASE</version>
    </dependency>

文件结构

在这里插入图片描述

实例 User类

package IOC;
//同类型
public class User {

    private  String  name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User(String name) {
        this.name = name;
    }
}

配置类

package IOC;

import org.springframework.context.annotation.*;

@Configuration
@ComponentScan("IOC")
public class BeanConfig {

    @Bean //声明返回项为一个bean实例
//  @Scope("Singleton") 默认单例
    public User1 getUserOne(){
        return new User1("Li");
    }

    @Bean
    @Profile("Two") //User2 不同配置
    public User2 getUserTwo(){
        return new User2("Two");
    }
    @Bean
    @Profile("AnotherTwo") //User2 不同配置
    public User2 getAnoUserTwo(){
        return new User2("AnotherTwo");
    }
    @Bean
    @Scope("prototype") //每次获取新建
    public  User3 getUserThree(){
       return  new User3("Three");
    }

    @Bean("four") //将Bean命名为four
    public User4 getUserFour(){
        return new User4("four");
    }
}

测试类

package IOC;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.lang.annotation.Annotation;

public class Main {

    public static void main(String [] args){
    	//加载配置类 BeanConfig
        AnnotationConfigApplicationContext context  = new AnnotationConfigApplicationContext(BeanConfig.class);
        User1 user1 = context.getBean(User1.class);
        User1 user11 = context.getBean(User1.class);
        User3 user3 = context.getBean(User3.class);
        User3 user31 = context.getBean(User3.class);
        //按名称 获取
        User4 user4 = (User4) context.getBean("four");
		//单例
        System.out.println(user1.getName());
        System.out.println(user11.getName());
        System.out.println(user1.equals(user11));
		//“多例”
        System.out.println(user3.getName());
        System.out.println(user31.getName());
        System.out.println(user3.equals(user3.getName()));
		//four
        System.out.println(user4.getName());
        context.close();
		//不同配置 测试方案
		//不加载配置类
        context = new AnnotationConfigApplicationContext();
        //在 系统环境 中设置使用名录
        context.getEnvironment().setActiveProfiles("AnotherTwo");
        //加载配置
        context.register(BeanConfig.class);
        //刷新容器
        context.refresh();
        User2 user2 =  context.getBean(User2.class);
        System.out.println(user2.getName());
        context.close();
    }
}

测试结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Shane_FZ_C/article/details/89003429
今日推荐