Spring annotation caching

My Spring application consists of two xml context configuration files, the first root-context.xml only scans non- @Controllerannotated beans:

<beans ...>
  <context:component-scan base-package="com.myapp.test">
    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
  </context:component-scan>
</beans>

While the second servlet-context.xml contains all spring-mvc installations and scans of @Controllerannotated beans

<beans:beans xmlns="http://www.springframework.org/schema/mvc" ...>
  <annotation-driven />
  <context:component-scan base-package="com.myapp.test">
    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
  </context:component-scan>
  ...
</beans:beans>

The configuration of the DispatcherServlet in web.xml is as follows:

<web-app ...>
  ...
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  ...

</web-app>

I wanted to try annotation-based caching, so I added the following beans definition in root-context.xml

<cache:annotation-driven/>

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
  <property name="caches">
    <set>
      <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="foo"/>
    </set>
  </property>
</bean>

And test this with an annotated class @Servicethat needs to be checked with root-context.xml

@Service
public FooService {
  @Cacheable("foo")
  public int getFoo() {
    System.out.println("cache miss");
    return new Random().nextInt(50);
  }
}

getFoo() , .

beans servlet-context.xml beans , .

? - .

+4
1

- .xml @Component beans context:component-scan

<context:component-scan base-package="com.myapp.test">
    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
  </context:component-scan>

use-default-filters="false"

 <context:component-scan base-package="com.myapp.test" use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
  </context:component-scan>

bean.

+5

Source: https://habr.com/ru/post/1525745/


All Articles