Spring initialization ApplicationContext Thread hosting practical application architecture concept

Source: Internet
Author: User
Tags hosting

Today I share a technical point, using spring initialization + thread takeover to maintain session state after the program starts.

First, a section of @test Unit test annotations, background development is very familiar, this is the test of local code used:

@RunWith (Springjunit4classrunner.  Class"classpath:applicationContext.xml")

Runwith and Contextconfiguration of the source and function is not fine explanation, unfamiliar can go to the source.

1: Let me take a @test unit test the code for the Operation data:

@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations="Classpath:applicationContext.xml") Public classruntest {@Autowired customerservices custserver;//services layer, injected into the DAO layer@Test Public voidTest () {Customer Customer=NewCustomer (); Customer.setcname ("Yu Root Sea"); Customer.setcinfo ("I am a fish! "); Customer.setcage (" -");    Custserver.inserttest (customer); }}

(1) Run the unit test again, the info log output:

 -: the: -,296INFO Defaulttestcontextbootstrapper:259-LoadeddefaultTestexecutionlistenerclassNames fromLocation [meta-inf/spring.factories]: [Org.springframework.test.context.web.ServletTestExecutionListener, Org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, Org.springframework.test.context.support.DependencyInjectionTestExecutionListener, Org.springframework.test.context.support.DirtiesContextTestExecutionListener, Org.springframework.test.context.transaction.TransactionalTestExecutionListener, Org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] -: the: -,313INFO Defaulttestcontextbootstrapper:185-Using testexecutionlisteners: [Or[email protected]146ba0ac, Org.springframework.test[email protected]4dfa3a9d, Org.springframewor[email protected]6eebc39e, Org.springfra[email protected]464bee09, Org.springframew[email PROTECTED]F6C48AC, Org.sp[email protected]13deb50e] -: the: -,390INFO Xmlbeandefinitionreader:317-Loading XML Bean definitions from classpath resource [Applicationcontext.xml] -: the: -,685INFO Genericapplicationcontext:578-Refreshing [email protected]0736d9:startup date [Mon] -  -: the: -Cst .]; Root of context Hierarchy -: the: -,777INFO Propertyplaceholderconfigurer:172-Loading Properties File from classpath resource [init.properties] -: the: -,970INFO Mlog:212-Mlog Clientsusingslf4j logging. -: the: to,123INFO C3p0registry:212-Initializing c3p0-0.9.5.2[Built ,-december- -  A: .:Geneva-0800; Debug?true; TraceTen] -: the: to,296INFO Version:Panax Notoginseng-Hhh000412:hibernate Core {5.0.8. Final} -: the: to,298INFO Environment:213-HHH000206:hibernate.properties not found -: the: to,299INFO Environment:317-Hhh000021:bytecode provider Name:javassist -: the: to,336INFO Version: the-Hcann000001:hibernate Commons Annotations {5.0.1. Final} -: the: to,416INFO Abstractpoolbackeddatasource:212-Initializing c3p0 pool ... com.mchange.v2.c3p0.ComboPooledDataSource [acquireincrement5, acquireretryattempts -, Acquireretrydelay +, Autocommitonclosefalse, automatictesttableNULL, Breakafteracquirefailurefalse, Checkouttimeout30000, ConnectioncustomizerclassnameNULL, Connectiontesterclassname, Com.mchange.v2.c3p0.impl.DefaultConnectionTester, Contextclassloadersource Caller, DataSourceName, 1bqudj89p1g46yu313x3lsl|41ab013, debugunreturnedconnectionstacktracesfalse, descriptionNULL, Driverclass-com.mysql.jdbc.Driver, extensions-so {}, factoryclasslocationNULL, forceignoreunresolvedtransactionsfalse, Forcesynchronouscheckinsfalse, Forceusenameddriverclassfalse, Identitytoken, 1bqudj89p1g46yu313x3lsl|41ab013, Idleconnectiontestperiod -, initialpoolsize5, Jdbcurl-Jdbc:mysql://127.0.0.1:3306/yugh?useunicode=true&characterencoding=utf-8, maxadministrativetasktime, 0, Maxconnectionage, 0, MaxIdleTime, maxidletimeexcessconnections, 0, Maxpoolsize, maxstatements  0, maxstatementsperconnection, 0, Minpoolsize, 5, Numhelperthreads, 3, preferredtestquery, NULL, Privilegespawnedthreads, False, properties, {user=******, password=******}, propertycycle-0, STATEMENTCA Chenumdeferredclosethreads, 0, Testconnectiononcheckin, false, Testconnectiononcheckout, Unreturnedconnectiontimeout, 0, Useroverrides, {}, Usestraditionalreflectiveproxies, false] -: the: to,633INFO dialect:156-hhh000400:using Dialect:org.hibernate.dialect.MySQLDialect -: the: to,671INFO Lobcreatorbuilderimpl:98-Hhh000423:disabling Contextual LOB creation asJDBC Driver reported JDBC version [3] Less than4 -: the: +,027INFO schemaupdate: the-hhh000228:running HBM2DDL Schema update -: the: +, -INFO Hibernatetransactionmanager:357-Using DataSource [com.mchange.v2.c3p0.combopooleddatasource[identitytoken-1bqudj89p1g46yu313x3lsl|41ab013, DataSourceName, 1bqudj89p1g46yu313x3lsl|41ab013]] of Hibernate sessionfactory forhibernatetransactionmanagerhibernate:SelectNext_val asId_val fromHibernate_sequence forupdatehibernate:update hibernate_sequenceSetNext_val=?whereNext_val=?Hibernate:insert into customer (cage, Cinfo, CNAME, id) VALUES (?, ?, ?, ?) -: the: +,487INFO Genericapplicationcontext:960-Closing [email protected]0736d9:startup date [Mon] -  -: the: -Cst .]; Root of context Hierarchy

(2) You can see that the @test unit test initializes all the configurations in the spring and spring files, because to manipulate the data objects, in most background unit tests, the purpose is to interact with the data.

@Test Summary: The @test unit test allows you to initialize spring and to load all the correct configuration parameters that have been configured to the spring file, although it runs briefly.

Ignore hibernate above, although the above test is hibernate as the persistence layer, all the knowledge points in this article are spring, including replacing other persistence layers with spring's data control.

2: The purpose of the initialization, the following will be used to take over the initialization of the operation, a few key points: (1) Initialization of the spring file (2) transaction with WHO, how to use, can success? (3) When does the thread take over?

Static objects are the only ones that keep the object unique and remain initialized, because when using the @test unit test, the annotation runwith reflects the test class and the method name, the actual function class entry has been obtained, and we initialize the Spring launcher without @test annotations to define the global static object.

(1): Initializes the spring file, the file loading method is I commonly used:

 Public Static New Classpathxmlapplicationcontext ("applicationcontext.xml");

(2): The transaction takes Spring: DataSource is the bean of the database

<bean id="transactionmanager"        class="  Org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="  dataSource">            <ref bean="dataSource" />        </property>    </bean>

Write down the static object that gets the transaction:

static final Platformtransactionmanager MANAGER = (platformtransactionmanager) context.getbean (" TransactionManager ");

(3): Data Control Object JdbcTemplate, formerly JdbcAccessor, the source of SQL-based datasource:

 Public Static Final JdbcTemplate jdbc_template = (jdbctemplate) context.getbean ("JdbcTemplate");
class= "Org.springframework.jdbc.core.JdbcTemplate" >        <property name= "DataSource" >            < Ref bean= "DataSource"/>        </property>    </bean>

(4) The configuration menu here is: Initialize Spring file + transaction + Data Control object, although all rely on spring, but it is a very good pure background project architecture, although in the persistence layer does not have hibernate so powerful various operations.

Finally, a spring initialization log:

09:43:35,326 INFO classpathxmlapplicationcontext:578-refreshing org[email protected]7ce6a65d:startup Date [Tue 08 09:43:35 CST 2017]; Root of context Hierarchy09:43:35,368 INFO xmlbeandefinitionreader:317-loading XML Bean Definitions fromclasspath resource [Applicationcontext.xml]09:44:21,994 INFO propertyplaceholderconfigurer:172-loading Properties file fromclasspath resource [init.properties]09:44:24,847 INFO mlog:212-mlog clients using SLF4J logging.09:44:25,007 INFO c3p0registry:212-initializing c3p0-0.9.5.2 [built 08-december-2015 22:06:04-0800; Debug?true; Trace:10]09:44:33,517 INFO abstractpoolbackeddatasource:212-initializing c3p0 Pool ... Com.mchange.v2.c3p0.ComboPooledDataSource [Acquireincrement, 5, acquireretryattempts, Acquireretrydelay , Autocommitonclose,false, automatictesttableNULL, Breakafteracquirefailurefalse, Checkouttimeout, 30000, ConnectioncustomizerclassnameNULL, Connectiontesterclassname, Com.mchange.v2.c3p0.impl.DefaultConnectionTester, Contextclassloadersource Caller, DataSourceName, 1bqudj89p1h4zfam1rricvn|62e8f862, debugunreturnedconnectionstacktracesfalse, descriptionNULL, Driverclass-com.mysql.jdbc.Driver, extensions-so {}, factoryclasslocationNULL, forceignoreunresolvedtransactionsfalse, Forcesynchronouscheckinsfalse, Forceusenameddriverclassfalse, Identitytoken-1bqudj89p1h4zfam1rricvn|62e8f862, Idleconnectiontestperiod, Initialpoolsize 5, Jdbcurl-Jdbc:mysql://127.0.0.1:3306/yugh?useunicode=true&characterencoding=utf-8, maxadministrativetasktime, 0, Maxconnectionage, 0, MaxIdleTime, maxidletimeexcessconnections, 0, Maxpoolsize, maxstatements  0, maxstatementsperconnection, 0, Minpoolsize, 5, Numhelperthreads, 3, preferredtestquery, NULL, Privilegespawnedthreads, False, properties, {user=******, password=******}, propertycycle-0, STATEMENTCA Chenumdeferredclosethreads, 0, Testconnectiononcheckin, false, Testconnectiononcheckout, Unreturnedconnectiontimeout, 0, Useroverrides, {}, Usestraditionalreflectiveproxies, false]

summarize the idea: (1) The initial loading of the spring file with the code---(2) The main portal defines a main method, after the various checks run, run-to (3) call the static initialization code, start the initial-----(4) Call Data control after the initial completion (5) After a series of background operations, the thread starts to take over-and (6) The code controls it to keep the session state running in the background.

Spring initialization ApplicationContext Thread hosting practical application architecture idea

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.