Spring 3基于Java的配置,替换XML - java

我最近配置了基于spring的maven项目,我只想用Java替换所有XML(POM除外)。我浏览了很多与此有关的文章和文档,但是,我在这里的原因是,我怀疑我想让你们解决这些问题。

众所周知,每个动态Web项目都有一个XML,在没有框架的情况下称为 web.xml

现在,如果我们集成一些框架,例如Struts,Spring,ORM等。
还必须配置它们,因此我们编写了另一个XML配置文件。

我配置了spring项目,所以我只有一个部署描述符,应用程序上下文和调度程序servlet。

WEB.XML

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-ctx.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

app-ctx.xml

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flow="http://www.springframework.org/schema/webflow-config"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context  
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/webflow-config 
                           http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
                           http://www.springframework.org/schema/jee 
                           http://www.springframework.org/schema/jee/spring-jee.xsd
                           http://www.springframework.org/schema/jms 
                           http://www.springframework.org/schema/jms/spring-jms.xsd
                           http://www.springframework.org/schema/lang 
                           http://www.springframework.org/schema/lang/spring-lang.xsd
                           http://www.springframework.org/schema/osgi 
                           http://www.springframework.org/schema/osgi/spring-osgi.xsd
                           http://www.springframework.org/schema/tx 
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/util 
                           http://www.springframework.org/schema/util/spring-util.xsd">

    <context:component-scan base-package="com.mzk.mavenproject1"/>

<!--    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/config_local.properties" />-->


</beans>

dispatcher-servlet.xml

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flow="http://www.springframework.org/schema/webflow-config"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"

       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context  
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc 
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd
                           http://www.springframework.org/schema/webflow-config 
                           http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
                           http://www.springframework.org/schema/jee 
                           http://www.springframework.org/schema/jee/spring-jee.xsd
                           http://www.springframework.org/schema/jms 
                           http://www.springframework.org/schema/jms/spring-jms.xsd
                           http://www.springframework.org/schema/lang 
                           http://www.springframework.org/schema/lang/spring-lang.xsd
                           http://www.springframework.org/schema/osgi 
                           http://www.springframework.org/schema/osgi/spring-osgi.xsd
                           http://www.springframework.org/schema/tx 
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/util 
                           http://www.springframework.org/schema/util/spring-util.xsd">

    <mvc:resources mapping="/resources/**" location="/resources/"  cache-period="31556926" />
    <context:component-scan base-package="com.mzk.mavenproject1"/>

    <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>    

    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <!--Turn off working out content type based on URL file extension, should fall back to looking at the Accept headers-->
        <property name="favorPathExtension" value="false" />
    </bean>   

    <!-- 2. HandlerMapping : Used default handler mapping internally -->

    <!-- 3. ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>   

</beans>

混乱:

我很困惑地知道,java需要多少个类来替换相同的类。我们需要三个java类还是两个就足够了?

因为,很多文章都演示了这两个java类,它们分别替换了web.xmldispatcher-servlet.xml,所以app-ctx.xml呢?

编辑:

 @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/", "home");
    }

要么

@Override
        public void addViewControllers(ViewControllerRegistry registry) {
           registry.addViewController("/").setViewName("home");
        }

控制器类

@Controller
public class HomeController {

    @RequestMapping(value="/")
    public ModelAndView showhomePage() {
        ModelAndView mav = new ModelAndView("home");
        mav.addObject("successMsg", "Congratulations! Your Cortana is Properly congigured");
        return mav;
    }
}

我还做了一个技巧,创建了一个全局index.jsp,并仅指定一个scriptlet,它将使用`sendRedirect()将请求重定向到Controller。

喜欢

@Override
            public void addViewControllers(ViewControllerRegistry registry) {
               registry.addViewController("/").setViewName("forward:/index.jsp");
            }

每当我面对404时,我都想不起来什么片段?

参考方案

如果我对它的理解很好,那么您想摆脱所有XML配置。

然后,首先,您必须实现WebApplicationInitializer来替换web.xml配置文件。您可以这样做:

public class CustomWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(RootConfig.class);

        ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext);
        servletContext.addListener(contextLoaderListener);

        AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
        webContext.register(MvcConfig.class);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

另一个步骤是为root上下文实现Spring配置,该配置将替换app-ctx.xml:

@Configuration
@EnableWebMvc
@ComponentScan({"com.mzk.mavenproject1.service", "com.mzk.mavenproject1.model"})
public class RootConfig {
// ... provide another custom beans when needed
}

最后一步是实现MVC的配置,该配置将替换dispatcher-servlet.xml:

@Configuration
@EnableWebMvc
@ComponentScan("com.mzk.mavenproject1.controller")
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Bean
    ViewResolver internalViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

// ... provide another custom beans when needed
}

关于类计数的问题-是的,您只能通过两个类做到这一点:CustomWebAppInitializerMvcConfig,并且所有内容只有一个上下文。
CustomWebAppInitializer.onStartup()方法主体将如下所示:

    AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
    webContext.register(MvcConfig.class);

    ContextLoaderListener contextLoaderListener = new ContextLoaderListener(webContext);
    servletContext.addListener(contextLoaderListener);

    DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

Spring XML中的公共值配置 - java

我有几个Spring bean,其中所有属性值之一都是相同的String值。有没有一种方法可以在XML中一次定义此String并在属性值设置的所有bean中引用它?<bean id="somebean" class="test.SomeBean"> <property name="prope…

Spring Security不允许加载CSS或JS资源 - java

该资源位于src / main / resources / static / css或src / main / resources / static / js下,我使用的是Spring Boot,安全级别为:@Configuration @EnableWebMvcSecurity @EnableGlobalAuthentication public clas…

Spring MVC拦截器映射问题 - java

我有这段XML:<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/statics/**" /> <bean class="com.company.website.servlet.StaticsHandlerIntercept…

Spring Boot如何在POST之后返回响应 - java

我想创建一个新客户并在创建客户后返回客户编号。客户编号必须是从50000开始的自动递增的唯一编号。到目前为止,我已经成功创建了一个客户,但是我不确定应该如何生成客户编号,将其保存到数据库中,并在触发POST时将其作为成功消息显示给用户。json下面是所需的响应;{ "customerNumber": "50002", …

Spring中的应用程序上下文有什么作用? - java

我昨天问了一个问题(Using Spring in standalone apps),有关如何在独立应用程序中使用Spring。由此得知,您只创建一次应用程序上下文对象。因此,现在的问题是(即使在评论中得到了部分回答)创建应用程序上下文时会发生什么?当您说时,Spring是否会创建这些豆子并将它们连接在一起new ClassPathXmlApplicatio…