Build an SSH framework more gracefully (using Java configuration)

Source: Internet
Author: User

The Times are progressing, and the drawbacks of a large number of XML-based configurations are obvious, as well as an interesting alternative to XML configuration and direct annotation configuration-javaconfig, which began to be incorporated into spring from a separate project in Spring 3.0. It combines the benefits of XML decoupling and Java compile-time checking. Javaconfig can be seen as an XML file, but it is written in Java. Now let's show you how to write spring+springmvc+hibernate based on Java config configuration.

Project is a MAVEN project created under the INTELLJ IDE with the following directory

  

 

In the traditional way, Servlets like Dispatchservlet are configured in the Web. xml file, but with the SERVLET3 specification and Spring3.1 enhancements, we can use Java to configure Dispatchservlet in the Servlet container, which shows the initialization class file

  

 Public classWebinitializerextendsAbstractannotationconfigdispatcherservletinitializer {//specifying a configuration class@OverrideprotectedClass<?>[] getrootconfigclasses () {return NewClass<?>[] {rootconfig.class }; } @OverrideprotectedClass<?>[] getservletconfigclasses () {return NewClass<?>[] {webconfig.class }; }        //map Dispatchservlet to "/"@Overrideprotectedstring[] Getservletmappings () {return NewString[] {"/" }; }   }

    

Creating Webinitializer requires inheriting Abstractannotationconfigdispatcherservletinitializer, Because any class that inherits the class will automatically configure the Dispatchservlet and Spring application contexts, Spring's application context is in the application's servlet context.

We can see that the underlying Abstractannotationconfigdispatcherservletinitializer expands and implements the Webapplicationinitializer, in the SERVLET3 environment, The container looks for classes in the classpath that implement the Javax.servlet.ServletContainerInitializer interface and configures the servlet container, and Spring provides an implementation of this interface named Springservletcontainerini Tializer, this class, in turn, looks for classes that implement Webapplicationinitializer and gives them the configured tasks to complete, So when we webinitializer expand the Abstractannotationconfigdispatcherservletinitializer and realize the Webapplicationinitializer, So when deployed to the Servlet3.0 container, the container will automatically find him and use it to configure the servlet context.

When Dispatchservlet is required to load the application context in Webinitializer, the bean defined in the Webconfig configuration class is used.

When using XML to configure spring, the spring listener must be configured and Contextloaderlistener, but what many people don't know is that Contextloaderlistener will create the spring web Another context in the app.

We want Dispatchservlet to load the beans that contain the Web components, such as the controller, the view resolver, and the processor mappings, and Contextloaderlistener to load the other beans in the app. These beans are typically the middle-tier and data-tier components that drive the application backend.

That is, the Webconfig class will be used to define the Dispatcherservlet application context of the Bean,rootconfig class that will be used to configure the Contextloadlistener created context of the bean

  

@Configuration @enablewebmvc//note-driven SPRINGMVC equivalent to <mvc:annotation-driven> in XML@ComponentScan ("Scau.zzf.web")//Enable component Scanning Public classWebconfigextendsWebmvcconfigureradapter {@Bean Publicviewresolver Viewresolver () {internalresourceviewresolver resolver=NewInternalresourceviewresolver (); Resolver.setprefix ("/web-inf/views/"); Resolver.setsuffix (". JSP"); Resolver.setexposecontextbeansasattributes (true); returnResolver; }    //configuring the processing of static resources requires that Dispatchservlet requests for static resources be forwarded to the default servlet in the servlet container@Override Public voidconfiguredefaultservlethandling (Defaultservlethandlerconfigurer configurer) {configurer.enable (); }}

  

@Configuration @import (hibernateconfig.class)//Import Hibernate configuration file@ComponentScan (basepackages={"Scau.zzf"}, Excludefilters={@ComponentScan. Filter (Type= Filtertype.custom, Value=rootconfig.webpackage.class)        }) Public classRootConfig {//Scan all packages except the Web     Public Static classWebPackageextendsRegexpatterntypefilter { PublicWebPackage () {Super(Pattern.compile ("Scau.zzf\\.web")); }    }}

Hbernateconfig as follows

@Configuration @propertysource (value={"Classpath:ds/ds-jdbc.properties"}, Ignoreresourcenotfound=true)//Ds-jdbc.properties loaded under the resources Public classhibernateconfig {@Value ("${jdbc.driverclassname}")    PrivateString Driverclassname; @Value ("${jdbc.url}")    PrivateString Jdbcurl; @Value ("${jdbc.username}")    PrivateString username; @Value ("${jdbc.password}")    PrivateString password; //Configure Sessionfactory@Bean Publicsessionfactory Sessionfactorybean () {Try{Localsessionfactorybean LSFB=NewLocalsessionfactorybean ();            Lsfb.setdatasource (DataSource ()); //Scan entity ClassesLsfb.setpackagestoscan ("Scau.zzf.entity"); Properties Props=NewProperties (); //set the dialect, using MySQLProps.setproperty ("dialect", "Org.hibernate.dialect.MySQLDialect");            Lsfb.sethibernateproperties (props);            Lsfb.afterpropertiesset (); Sessionfactory Object=Lsfb.getobject (); returnobject; } Catch(IOException e) {return NULL; }    }    //Configure DataSource@Bean PublicDataSource DataSource () {basicdatasource DS=NewBasicdatasource ();        Ds.setdriverclassname (Driverclassname);        Ds.seturl (Jdbcurl);        Ds.setusername (username);        Ds.setpassword (password); returnds; } @Bean Public Staticpropertysourcesplaceholderconfigurer Placeholderconfigurer () {return Newpropertysourcesplaceholderconfigurer ();}}

Entity classes are as follows

  

@Entity @table (catalog= "Hibernate", name = "Users") Public classUser {@ColumnPrivateString username; @ColumnPrivateString password; @ColumnPrivateString sex; @ColumnPrivateString address; @ColumnPrivate intenabled; //Generatedvalue Overriding the default access policy for @id@Id @GeneratedValue (Strategy=generationtype.identity)//@GenericGenerator is defined in hibernate, generating a rough generation of primary key values using various primary keys built into hibernate//@GenericGenerator (name = "Hibernate-uuid", strategy = "uuid")//@GeneratedValue (generator = "Hibernate-uuid")    Private intID;  Public intgetenabled () {returnenabled; }     Public voidSetEnabled (intenabled) {         This. Enabled =enabled; }     PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. Address =address; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }     PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }}

Testing in the context of test

  

@RunWith (Springjunit4classrunner.  Class= {webconfig.  Class, RootConfig. class }) @WebAppConfigurationpublicclass  servicetest {      @Autowired      Private  userservice userservice;    @Test    publicvoid  userservicetest () {        user User= Userservice.finduser (1);        System.out.println (User.getusername ());}    }

In the test environment, the three annotations on the class must be configured, or else an error will occur.

  

Build an SSH framework more gracefully (using Java configuration)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.