1. Understand spring
Spring is an open-source control inversion (inversion of control, IOC) and AOP-oriented container framework. Its main goal is to simplify enterprise development.
(1) IOC control inversion:
public class PersonServiceBean { private PersonDao personDao = new PersonDaoBean(); public void save(Person person){ personDao.save(person); }}
Persondaobean is created and maintained inside the application. The so-called control inversion means that the application itself is not responsible for the creation and maintenance of dependent objects, and the creation and maintenance of dependent objects are the responsibility of external containers. In this way, the control is transferred from the application to the external container, and the transfer of control is called inversion. [Dependency object: persondao. An application can be seen as a self-written method, while an external container is a framework, and spring is one of them. It can be used to create and maintain dependency objects.]
(2) Dependency injection:
When we assign the dependency object to the external container for creation, the personservicebean class can be changed to the following:
Public class personservicebean {private persondao; // Let the container inject the created dependency object into the personservicebean through the constructor parameter. Of course, you can also use the setter Method for injection. Public personservicebean (persondao) {This. persondao = persondao;} public void save (person) {persondao. Save (person );}}
Dependency injection refers to the Dynamic Injection of dependent objects into components by external containers during runtime.
[Here, a persondao parameter is specified in the constructor to inject the dependent object instance (class implementing this interface) into the personservicebean. In addition, you can also use the Set Method for injection]
(3) Why use spring?
Introducing spring in a project immediately brings the following benefits:
- Reduce the coupling between components to achieve decoupling between different layers of software. Controller-> service-> Dao
- You can use many services provided by containers, such as transaction management and message service. When we use containers to manage transactions, developers no longer need to manually control the transactions or handle complex transaction propagation.
- The container supports the singleton mode, and developers no longer need to write their own implementation code.
- The container provides the AOP technology, which can easily implement functions such as permission interception and runtime monitoring.
- Container provides many auxiliary classes that can accelerate application development, such as jdbctemplate and hibernatetemplate.
- Spring provides integration support for mainstream application frameworks, such as Hibernate, JPA, and struts, to facilitate application development.
- Spring provides many services:
- If spring is used, you do not need to manually control transactions.
Hibernate transaction operation: Public void save () {session = sessionfactory. getcurrentsession ();
Session. begintransaction ();
Info info = new info ("Chuanzhi podcast"); Info. setcontent ("the most powerful Java training institution in China"); Session. Save (Info );
Session. gettransaction (). Commit ();
} JDBC transaction operation: Connection conn = NULL; try {.......
Conn. setautocommit (false );
Statement stmt = conn. createstatement (); stmt.exe cuteupdate ("Update person where name = 'Ye Tian '");
Conn. Commit ();
.....
} Catch (exception e ){
Conn. rollback ();} finally {conn. Close ();}
- If spring is used, it does not need to handle complicated transaction propagation behaviors.
Public void payment () {bean1.update (); // update bean2.save (); // record operation logs} If spring is not used, what should we do? 1st possible business requirements: bean1.update () and bean2.save () are required to be executed in the same transaction. 2nd possible business requirements: operation logs must be recorded regardless of whether the bean1.update () transaction is successful. Public class bean1 {public void Update () {// note: the following code is omitted: Connection conn = NULL; Conn. setautocommit (false); statement.exe cuteupdate ("update account set amount =? Where id =? ") ;}} Public class bean2 {public void save () {// note: the following code is omitted: Connection conn = NULL; Conn. setautocommit (false); statement.exe cuteupdate ("insert into log (content) values (?) ");}
Solution:
With spring, we only need to configure declarative transaction attributes to easily implement these two business requirements. bean1.update () and bean2.save () must be executed in the same transaction. logs must be recorded regardless of whether the bean1.update () transaction is successful. @ Transactional (propagation = propagation. required) Public void payment () {bean1.update (); // update the amount bean2.save (); // record the log} public class bean1 {@ transactional (propagation = propagation. required) Public void Update () {executeupdate ("update account set amount =? Where id =? ") ;}} Public class bean2 {@ transactional (propagation = propagation. requiresnew) Public void save () {executeupdate (" insert into log (content) values (?) ");}}
* Division of lightweight and heavyweight concepts
Some people often ask whether spring belongs to a lightweight framework or a weight framework? Whether an application is lightweight or heavyweight depends on how many services it uses. the more services you use, the more work containers need to do for common Java objects, which will inevitably affect the application release time or running performance.
For spring containers, it provides many services, but these services are not opened by default for the application. The application requires a certain service and also needs to specify to use this service. If the application uses few services, for example, if we only use spring core services, we can think that the application is lightweight at this time. If the application uses most of the services provided by spring, then the application is heavyweight. Currently, the EJB container is a heavyweight because it provides all the functions of the EJB specification for the application by default.
2. Build the environment
Spring download address: http://www.springsource.org/download
Decompress the package, find the following JAR file in the decompressed directory, and copy it to the class path.
Dist \ spring. Jar
Lib \ Jakarta-commons \ commons-logging.jar
If you use aspect programming (AOP), you also need the following JAR files
LIB/aspectj/aspectjweaver. jar and aspectjrt. Jar
LIB/cglib/cglib-nodep-2.1_3.jar
If you use annotations in the JSR-250, such as @ resource/@ postconstruct/@ predestroy, you also need the following JAR files
Lib \ J2EE \ common-annotations.jar
Configuration file template:
<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> ..... </beans> the configuration template can be obtained from the spring reference manual or spring example. The name of the configuration file can be arbitrary, and the file can be stored in any directory. However, considering its versatility, the configuration file is generally placed in a class path.
3. "No help information is available when you compile the spring configuration file"
Because the spring schema file is on the network, if the machine cannot connect to the network, the prompt message cannot be displayed when writing the configuration information. There are two solutions:
1. If the machine accesses the Internet, eclipse automatically downloads the schema file from the network and caches it on the hard disk.
2. Manually add a schema file using the following method:
Windwos-> preferences-> myeclipse-> files and editors-> XML-> xmlcatalog
Click "add", select URI in the key type in the window that appears, select "File System" in location, and then select the spring-beans-2.5.xsd in the Dist/Resources Directory of the spring extract directory,
Do not close the window when you return to the settings window. Change the key type in the window to schema location,
Key to http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
4. JUnit Testing
Unit testing is a good function. You can test a method separately.
Create a new "JUnit Test Case" in myeclipse and select new JUnit 4 Test
Enter the name of test and the method to be created.
Finally, if you are prompted that no JUnit 4 exists in the current build path, you must add it. The JUnit 4 added to the path is stored during myeclipse blue edition installation.
As shown in:
Class under test indicates the test class, which can be left unspecified
5. First test example:
Beans. 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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="personService" class="com.yinger.service.impl.PersonServiceBean"></bean> </beans>
Interface: personservice
package com.yinger.service;public interface PersonService { public void save();}
Implementation class: personservicebean
package com.yinger.service.impl;public class PersonServiceBean implements com.yinger.service.PersonService{ public void save() { System.out.println("save"); }}
JUnit test:
package com.yinger.test;import org.junit.BeforeClass;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.yinger.service.PersonService;public class SpringTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void testSave() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); PersonService ps = (PersonService)ctx.getBean("personService"); ps.save(); }}
Okay, run as-> JUnit Test
The result is: save is output in the last row! The example is successful!
Log4j: warn no appenders cocould be found for logger (Org. springframework. Context. Support. classpathxmlapplicationcontext ).
Log4j: Warn please initialize the log4j system properly.
Save
Document structure directory:
Check the written code carefully, which is hard to understand IOC (control reversal!