Could annotation based and xml based configuration

2019-07-19 06:28发布

问题:

I've been working on a project where controllers have been written extending Controller classes. Could I configure and use the POJO based Controllers as well (using @Controller) in the same application?

Many thanks

回答1:

Thanks jamestastic and skaffman, its working all fine now :)

Below are the lines needed to to be addeded to the web configuration file to have them working together:

<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:context="http://www.springframework.org/schema/context"                    ...line1
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd                        
            http://www.springframework.org/schema/context                           ...line2
        http://www.springframework.org/schema/context/spring-context-2.5.xsd">  ...line3



    <context:annotation-config/>   ...line4

    <context:component-scan base-package="myPackage"/>  ...line5

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>  ...line6

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>   ...line7

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>  ...line8

</beans>

I was too lazy to not to add line 8 in my main application.

Many thanks



回答2:

Absolutely. You can mix them together as much as you choose. DispatcherServlet should recognise both old-style and new-style controllers together in the same app.



回答3:

Yes you can. You'll need to include the Spring JavaConfig project library, as annotation configuration was not part of the 2.5 core.

Here is an example I wrote a while back comparing Google Guice with Spring. Toward the bottom (look for @ImportXml), I show how you can combine Spring XML configuration with annotation configuration. The configuration looks like this:

@Configuration
@ImportXml(locations = "classpath:com/earldouglas/guicespringjc/spring/config.xml")
public class XmlSpringConfiguration {
}

See the Spring Reference regarding combining XML and Annotation configuration. This is from the documentation for Spring 3, but it should still apply (with perhaps minor changes in class names and paths from the old Spring JavaConfig project).



回答4:

In Spring >= 3.0 use @ImportResource annotation

@Configuration
@ImportResource({ "classpath:/path/to/spring.xml", })
public class AppConfig {
}