配置在什么上下文中

时间:2017-05-16 13:42:05

标签: spring spring-mvc spring-bean

我有一个拥有所有业务bean的根上下文(它是根上下文)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd">

      <!-- Root Context: defines shared resources visible to all other web components -->

    <context:annotation-config />
    <context:component-scan base-package="it.mypack">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />    
    </context:component-scan>

</beans>

和只有控制器bean(它是root的子)的servlet-context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
      <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

      <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />


    <context:annotation-config />
    <context:component-scan base-package="it.mypack">
    <context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
</beans>

我想添加一个Configuration类,以便以编程方式创建一些bean。我的问题是:这些bean将成为root-context或servlet-context的一部分?

我的配置:

 @Configuration
 public class AppConfig {

     @Bean
     public ArrayList<String> myBean() {
         ArrayList<String> std=new  ArrayList<String>();
         std.add("ciao");
         return std;
     }
 }

我问这个是因为我不想创建重复的bean。如果您读取我的上下文代码,则不允许此问题,根上下文已为所有组件启用了组件扫描,除了控制器和servlet-context已启用仅针对Controller的组件扫描...所以我的问题是bean ArrayList myBean(在我的配置中声明) class)有上下文根或servlet上下文吗?你确定春天不会创建重复的bean吗?拜托,你能解释一下这种行为吗?

1 个答案:

答案 0 :(得分:0)

“根上下文已启用除控制器和servlet上下文之外的所有组件的组件扫描,仅为Controller启用组件扫描”

AppConfig具有配置注释,因此将位于根上下文中。因为内部的任何内容都将在根上下文中。