Spring手动注册Bean(代码方式)

第一种(ClassPathXmlApplicationContext)

1.定义一个对象

public class HelloWord {
    private String name = "lsr";
    public String say(){
        return "hello "+name;
    }
}

2.此种方式使用传统xml方式启动spring容器(xml里面没有任何配置)

public static void main(String[] args) {
       ClassPathXmlApplicationContext context = new     
      ClassPathXmlApplicationContext("spring/spring.xml");
       // 获取spring bean 工厂 手动注册bean
       context.getBeanFactory().registerSingleton("lisr", new HelloWord());
       // 启动spring容器
       context.start();

       // 从上下文获取bean
       HelloWord helloWord = context.getBean("lisr", HelloWord.class);
       System.out.println(helloWord.say());
   }

xml内容



第二种(springboot)

1.创建一个DefinitionRegistryPostProcessor

/**
@Configuration
或
@Component
或
@Bean定义
**/
@Configuration
public class DefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) 
throws BeansException {

    }

    /**
     * 先执行postProcessBeanDefinitionRegistry方法
     * 在执行postProcessBeanFactory方法
     */
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) 
        throws BeansException {
        // 第一种 : 手动注入
        // 注册bean
        registerBean(registry, "hello", HelloWord.class);
        registerBean(registry, "helloWord", HelloWord.class);
    }
/**
注册bean
**/
 private void registerBean(BeanDefinitionRegistry registry, String name, Class beanClass) {
        RootBeanDefinition bean = new RootBeanDefinition(beanClass);
        registry.registerBeanDefinition(name, bean);
    }
}

2.测试能否在spring上下文获取该bean

@SpringBootApplication
public class ApplicationBoot {
    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(ApplicationBoot.class);
        HelloWord helloWord = applicationContext.getBean("hello", HelloWord.class);
        System.out.println(helloWord.say());
    }
}

你可能感兴趣的:(Spring手动注册Bean(代码方式))