Build an SSH framework more elegantly (configured using java) and build an ssh framework java

Source: Internet
Author: User

Build an SSH framework more elegantly (configured using java) and build an ssh framework java

The times are constantly improving, and the disadvantages of a large number of xml-based configurations are also obvious. In addition to XML configuration and direct annotation-based configuration, there is also an interesting way to choose-JavaConfig, it is incorporated into Spring from an independent project in Spring 3.0. It combines the advantages of XML decoupling and JAVA compilation check. JavaConfig can be viewed as an XML file, but it is written in Java. Now we will show you how to compile spring + springmvc + hibernate Based on java Config.

The project is a maven project created under intellij IDE. The directory is as follows:

  

 

In the traditional way, servlets such as DispatchServlet are configured on the web. xml file, but with the help of the Servlet3 specification and Spring3.1 enhancement, we can use java to configure DispatchServlet In the Servlet container. The following shows the initialization class file

  

Public class WebInitializer extends actannotationconfigdispatcherservletinitializer {// specify the configuration Class @ Override protected class <?> [] GetRootConfigClasses () {return new Class <?> [] {RootConfig. class };}@ Override protected Class <?> [] GetServletConfigClasses () {return new Class <?> [] {WebConfig. class };}// map DispatchServlet to "/" @ Override protected String [] getServletMappings () {return new String [] {"/"};}

 

    

To create a WebInitializer, you must inherit AbstractAnnotationConfigDispatcherServletInitializer. Because any class that inherits this class automatically configures DispatchServlet and Spring application context, Spring application context is located in the Servlet context of the application.
  

We can see that the underlying acactannotationconfigdispatcherservletinitializer extends and implements WebApplicationInitializer. In the Servlet3 environment, the container will find and implement javax in the class path. servlet. the class of the ServletContainerInitializer interface and configures the Servlet container. spring provides the implementation of this interface named SpringServletContainerInitializer, this class will, in turn, find the class that implements WebApplicationInitializer and hand over the configuration task to them for completion. Therefore, when our WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer, it also implements WebApplicationInitializer. When deployed to the Servlet3.0 container, the container will automatically discover it and use it to configure the Servlet context.

In WebInitializer, when DispatchServlet is required to load the application context, bean defined in the WebConfig configuration class is used.

When using xml to configure spring, you must configure the spring listener and ContextLoaderListener. However, many people do not know that ContextLoaderListener will create another context in the spring web application.

We want DispatchServlet to load beans containing Web components, such as controllers, view parsers, and processor ing, while ContextLoaderListener will load other beans in the application, these beans are usually the middle layer and data layer components that drive the application backend.

That is to say, the WebConfig class will be used to define the bean of the DispatcherServlet application context, and the RootConfig class will be used to configure the bean of the context created by ContextLoadListener.

  

@ Configuration @ EnableWebMvc // The annotation driver springMVC is equivalent to <mvc: annotation-driven> @ ComponentScan ("scau. zzf. web ") // enable component scan public class WebConfig extends webmvcjavaseradapter {@ Bean public ViewResolver viewResolver () {InternalResourceViewResolver resolver = new InternalResourceViewResolver (); resolver. setPrefix ("/WEB-INF/views/"); resolver. setSuffix (". jsp "); resolver. setExposeContextBeansAsAttributes (true); return resolver;} // configure the processing of static resources, the DispatchServlet request for static resources must be forwarded to the default servlet in the Servlet container @ Override public void configuredefaservservlethandling (defaservservlethandlerconfigurer configurer) {configurer. enable ();}}

 

  

@ Configuration @ Import (HibernateConfig. class) // import the Hibernate configuration file @ ComponentScan (basePackages = {"scau. zzf "}, excludeFilters = {@ ComponentScan. filter (type = FilterType. CUSTOM, value = RootConfig. webPackage. class)}) public class RootConfig {// scan all packages except the web, public static class WebPackage extends RegexPatternTypeFilter {public WebPackage () {super (Pattern. compile ("scau. zzf \\. web "));}}}

 

HbernateConfig is as follows:

@ Configuration @ PropertySource (value = {"classpath: ds/ds-jdbc.properties"}, ignoreResourceNotFound = true) // ds-jdbc.propertiespublic class HibernateConfig loaded under resources {@ Value ("$ {jdbc. driverClassName} ") private String driverClassName; @ Value (" $ {jdbc. url} ") private String jdbcURL; @ Value (" $ {jdbc. username} ") private String username; @ Value (" $ {jdbc. password} ") private String password; // configure sessionFactory @ Bean public SessionFactory sessionFactoryBean () {try {LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean (); lsfb. setDataSource (dataSource (); // scan the entity class lsfb. setPackagesToScan ("scau. zzf. entity "); Properties props = new Properties (); // sets the dialect using MySql props. setProperty ("dialect", "org. hibernate. dialect. mySQLDialect "); lsfb. setHibernateProperties (props); lsfb. afterPropertiesSet (); SessionFactory object = lsfb. getObject (); return object;} catch (IOException e) {return null ;}// configure DataSource @ Bean public DataSource dataSource () {BasicDataSource ds = new BasicDataSource (); ds. setDriverClassName (driverClassName); ds. setUrl (jdbcURL); ds. setUsername (username); ds. setPassword (password); return ds ;}@ Beanpublic static PropertySourcesPlaceholderConfigurer placeHolderConfigurer () {return new PropertySourcesPlaceholderConfigurer ();}}

 

The object class is as follows:

  

@ Entity @ Table (catalog = "hibernate", name = "users") public class User {@ Column private String username; @ Column private String password; @ Column private String sex; @ Column private String address; @ Column private int enabled; // GeneratedValue overwrites the default access policy @ id @ GeneratedValue (strategy = GenerationType. IDENTITY) // @ GenericGenerator is defined in hibernate. Use the various built-in primary keys of hibernate to generate a rough primary key value. // @ GenericGenerator (name = "hibernate-uuid ", strategy = "uuid") // @ GeneratedValue (generator = "hibernate-uuid") private int id; public int getEnabled () {return enabled;} public void setEnabled (int enabled) {this. enabled = enabled;} public String getAddress () {return address;} public void setAddress (String address) {this. address = address;} public String getSex () {return sex;} public void setSex (String sex) {this. sex = sex;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public int getId () {return id;} public void setId (int id) {this. id = id;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password ;}}

 

Test in the Test environment

  

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = {WebConfig.class, RootConfig.class})@WebAppConfigurationpublic class ServiceTest {      @Autowired    private UserService userService;    @Test    public void userServiceTest(){        User user=userService.findUser(1);        System.out.println(user.getUsername());    }}

 

In the test environment, the three annotations on the class must be configured. Otherwise, errors may occur.

  

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.