Spring Pure Java Annotated development (i)

Source: Internet
Author: User

Accustomed to using XML files to configure spring, now try to configure spring with pure Java code.

In fact, the pure Java configuration of spring is simply the process of converting the contents of a bean tag through annotations into a bean object, nothing mysterious.

To configure the AppConfig file first:

The configured English is called the configuration, so before the class of the Java configuration file, in order to illustrate the category that this class belongs to the configuration file, add such a label: @Configuration used to identify this class is a configuration class; then the @componentscan tag. Is it familiar? Yes, this is a label that represents the scan range, followed by an attribute basepackages to indicate which package to manage the bean under, and how to use it when configured in the XML file, and if it is a multi-pack sweep, enclose it in curly braces, separated by commas. Others, such as @EnableScheduling and @EnableAspectJAutoProxy, etc., can be added as needed.

In this file, I configured a database. First, through the @autowired to inject datasource, and then configure a @bean, is to write a DataSource instance is ok. Other, such as Shiro configuration and so on can be done here, the same way as data. Defining a new interceptor can also be done here, and it is necessary to note that the interceptor's bean needs to add a name attribute that defines the name of the interceptor for easy reference in Web. Xml.

Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.config.BeanPostProcessor;ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.context.annotation.ComponentScan;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.context.annotation.EnableAspectJAutoProxy;ImportOrg.springframework.core.io.ClassPathResource;ImportOrg.springframework.core.io.Resource;Importorg.springframework.scheduling.annotation.EnableScheduling;Importorg.springframework.util.FileCopyUtils;ImportJavax.servlet.Filter;ImportJavax.sql.DataSource;ImportJava.io.FileReader;Importjava.io.IOException, @Configuration @enablescheduling@enableaspectjautoproxy@componentscan (basepackages = {"Com.lab.service", "Com.lab.task", "com.lab.security"}) Public classApplicationconfig {@AutowiredPrivateDataSource DataSource; @Bean PublicIDBI Database () {IDBI dbi=NewDBI (DataSource); Logger.debug ("DBI: {}", DBI); returnDBI; }//..... }

The second is to configure the Webconfig file:

As with the previous one, the first thing you need to add is the @configuration tag, and a different one is the need for the @enablewebmvc tag to turn on MVC mode. Of course there are @componentscan tags, using the same method as before, requires the definition of the Basepackages attribute. Labels such as @EnableAspectJAutoProxy can also be added on demand.

The definition here has such as Setprefix and setsuffix content, concrete according to actual increase or decrease.

ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.context.annotation.ComponentScan;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.context.annotation.EnableAspectJAutoProxy;Importorg.springframework.web.servlet.config.annotation.*;Importorg.springframework.web.servlet.view.internalresourceviewresolver;@ Configuration@enablewebmvc@enableaspectjautoproxy@componentscan (Basepackages= {"Com.lab.controller" }) Public classWebconfigextendsWebmvcconfigureradapter {@Bean Publicinternalresourceviewresolver Viewresolver () {internalresourceviewresolver resolver=NewInternalresourceviewresolver (); Resolver.setprefix ("/web-inf/view/"); Resolver.setsuffix (". JSP"); returnResolver; }}

Define the Dataconfig file:

I have injected the database definition directly in appconfig because of the definition of the specific database connection I am doing here.

@Configuration is necessary, and then I define a property @Profile ("Data") to illustrate the purpose of this class. Then you define a @bean (name= "DataSource"), which is the database connection pool, the linked user name, the password, the wait time-out, and so on, a series of database configuration.

ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.context.annotation.Profile;ImportCom.alibaba.druid.pool.DruidDataSource;@Configuration @profile ("Data") Public classDevConfig {
/* Here I use the properties file to define the database, or you can write directly in the code *
/
Private Static FinalString databaseconfig = "Datasource.properties"; @Bean (Name= "DataSource") PublicDataSource DataSource () {Druiddatasource DataSource=NewDruiddatasource (); InputStream instream=NULL; Try{Properties prop=NewProperties (); Instream=getclass (). getClassLoader (). getResourceAsStream (databaseconfig);prop.load (instream); String Datastyle= Prop.getproperty ("Data.style");Datasource.seturl (Prop.getproperty (Datastyle+ ". Data.url") + ":" + prop.getproperty (Datastyle + ". Data.database")); Datasource.setusername (Prop.getproperty (Datastyle+ ". Data.user")); Datasource.setpassword (Prop.getproperty (Datastyle+ ". Data.password")); /*Configure filtering*/datasource.setfilters (Prop.getproperty (Datastyle+ ". Data.filters")); /*Configure initialization size, minimum, maximum*/datasource.setinitialsize (Integer.parseint (Prop.getproperty (Datastyle+ ". Data.initialsize"))); Datasource.setminidle (Integer.parseint (Prop.getproperty (Datastyle+ ". Data.minidle"))); Datasource.setmaxactive (Integer.parseint (Prop.getproperty (Datastyle+ ". Data.maxactive"))); /*Configure the time to get the connection wait timeout*/datasource.setmaxwait (Integer.parseint (Prop.getproperty (Datastyle+ ". Data.maxwait"))); /*How often the configuration interval is detected to detect idle connections that need to be closed, in milliseconds*/Datasource.settimebetweenevictionrunsmillis (Integer.parseint (Prop.getproperty (datastyl E+ ". Data.timebetweenevictionrunsmillis"))); /*configures the minimum lifetime of a connection in a pool, in milliseconds*/Datasource.setminevictableidletimemillis (Integer.parseint (Prop.getproperty (Datastyle /c8>+ ". Data.minevictableidletimemillis"))); } Catch(FileNotFoundException filenotfoundexception) {filenotfoundexception.printstacktrace (); } Catch(IOException IOException) {ioexception.printstacktrace (); } Catch(SQLException SQLException) {sqlexception.printstacktrace (); } returnDataSource; }}

Once these are all defined, it is OK to configure them in the Web. xml file.

    <!--Context configuration file address -    <Context-param>        <Param-name>Contextconfiglocation</Param-name>        <Param-value>Com.bell.lab.springconfig.DevConfig, Com.bell.lab.springconfig.ApplicationConfig</Param-value>    </Context-param>
    <servlet>        <Servlet-name>Springdemoservlet</Servlet-name>        <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>        <Init-param>            <Param-name>Contextclass</Param-name>            <Param-value>Org.springframework.web.context.support.AnnotationConfigWebApplicationContext</Param-value>        </Init-param>        <Init-param>            <Param-name>Contextconfiglocation</Param-name>            <Param-value>Com.bell.lab.springconfig.WebConfig</Param-value>        </Init-param>        <Load-on-startup>1</Load-on-startup>    </servlet>    <servlet-mapping>        <Servlet-name>Springdemoservlet</Servlet-name>        <Url-pattern>/</Url-pattern>    </servlet-mapping>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>data</param-value>
</context-param>

At this point, with the spring-application.xml in the configuration effect is the same, the overall more consistent with the Java habit.

PS: In fact, even if the Web. xml file, can also be configured in the form of Java code, but I feel a little trouble, there is no explanation, interested can find the relevant data to configure.

Spring Pure Java Annotated development (i)

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.