spring注解驱动开发3-Bean名称自定义

  1. 获取bean:
    @Bean:
    ctx.getBean("person", Person.class);
    @Bean(“personJson”):
    ctx.getBean("personJson", Person.class);
  2. 括号里自定义bean名称: 如果没有定义, 默认是办法名(person) : @Bean(“personJson”)
    @Test
    public void testBeanName() {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ScopeConfig.class);
        Arrays.stream(ctx.getBeanDefinitionNames()).forEach(System.out::println);

        Person p = ctx.getBean("personJson", Person.class);
        System.out.println(p);

    }
package com.niewj.config;

import com.niewj.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;

@Configuration
public class ScopeConfig {

    /**
     * singleton单例默认是先初始化的; prototype 默认是提早初始化, 只有getBean才会初始化结构!
     * singleton单例的如果想提早初始化, 能够在@Bean同时加注解@Lazy
     * @return
     */
    @Scope("singleton")
    @Lazy
    @Bean("personJson")
    public Person person() {
        return new Person("json", 22);
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理