繁体   English   中英

为什么Spring无法自动装配一个称为环境的bean?

[英]Why can't Spring autowire a bean called environment?

下面的代码创建一个父上下文,并将名为Environment的类放入具有通过AnnotationBeanNameGenerator生成的名称environment的上下文中。 然后将其自动连接到处于子上下文中的TestChild中。

但是,随着AnnotationBeanNameGeneratorEnvironment类生成environment的名称,当我启动子上下文(Web服务器)时,出现一个错误,提示它无法自动装配Bean。 如果我将bean的名称更改为固定的名称(即guid),则可以正常工作。

我在下面的代码中使用了组件扫描,但是这些是我项目中唯一的类。

@RestController
public class TestChild {

    @Autowired
    public TestChild(Environment environment) { }
}

-

public class Environment {

    public Environment() {
        System.err.print("hey");
    }
}

-

AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext();
parentContext.addBeanFactoryPostProcessor(new BeanDefinitionRegistryPostProcessor() {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        BeanDefinition bd = new RootBeanDefinition(Environment.class, null, null);
        AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();
        registry.registerBeanDefinition(generator.generateBeanName(bd, registry), bd);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { }
});
parentContext.refresh();

AnnotationConfigWebApplicationContext childContext = new AnnotationConfigWebApplicationContext();
childContext.setParent(parentContext);
childContext.scan("child");
ServletContextHandler contextHandler = new ServletContextHandler();

contextHandler.addServlet(new ServletHolder(new DispatcherServlet(childContext)), "/*");
contextHandler.addEventListener(new ContextLoaderListener(childContext));

Server server = new Server(8080) {{ setHandler(contextHandler); }};
server.start();
server.join();

您可能会遇到此问题,因为应用程序上下文已经包含一个名为environment的Bean,作为核心Spring功能的一部分。

您可以在下面看到此内容:

org.springframework.core.env.Environment e = applicationContext.getBean("environment");
LOGGER.info(e.getClass().getName());
//prints: org.springframework.web.context.support.StandardServletEnvironment

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM