springBoot 手动注入Bean

时间:2024-03-12 13:27:44

 

1.创建一个DefinitionRegistryPostProcessor :

package com..aop_mybatis;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Configuration;

@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());
    }
}


3.测试类:

package com..aop_mybatis;

public class HelloWord {

public void say() {
System.out.println("111");
}
}

 

结果: