Spring Learning Notes

Source: Internet
Author: User

[1] Setting up the environment

1. Add a jar Package

Using spring requires

Sring.jar
Commons-loggin.jar

If using an AOP component requires

Aspectjweaver.jar
Aspectjrt.jar

If the annotations using jsr-250 require

Commom-annotations.jar

2. Add Bean.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 ">

</beans>


3. Testing
@Test
public void instancespring () {
ApplicationContext CTX = new Classpathxmlapplicationcontext ("Beans.xml");
}

4. Run. If you set it up by stating that the spring environment

[2] Adding a bean

Adding a bean is equivalent to defining a component that is used to implement a specific function.
The bean defined here is equivalent to giving you a simple and convenient way to invoke this component to implement the functionality you want to accomplish.
ID attribute: Equivalent to defining the alias of your Bean, if the bean alias needs to use a character that is not supported by ID (/user/list), you can use name instead

Class attribute: This is what you do with this function. The class path of the Bean

Scope Property: The default is Singleton, which is single-instance mode, each time Getbean ("id") gets the same instance, if set to prototype, which is the prototype mode, each time you get a newly created instance.

Lazy-init property: Lazy-init= "false" to initialize the load, indicating that the spring is started, immediately instantiated. Is true, the instantiation is deferred. (The Lazy-init setting only works on beans with the Scop property of Singleton)

Init-method: The method to invoke after the Bean is instantiated (the method defined in the bean).

Destroy-method:bean the method to be called before removing from the container.

Autowire: The method by which attributes are automatically assembled.

For each of these attributes, the ID and class are necessary, and others can be omitted. For example, if the value of Autowire is set, it indicates that automatic assembly is required, otherwise it is manually assembled.
eg
<bean id= "Personservice" class= "Cn.soldier.service.impl.PersonServiceBean" scope= "singleton" lazy-init= "false" Init-method= "Init" destroy-method= "Destroy"/>

[3] object injected into component bean (inversion of control)
There are three ways to accomplish this:
The first type:
The constructor parameter allows the container to inject the created dependent object
1.personservicebeanc.ass
Private Persondao PersonDao2;
Private String name2;
Omit getter and setter
Public Personservicebean (Persondao PersonDao2, String name2) {
This.persondao2 = PersonDao2;
This.name2 = name2;
}
2.beans.xml
<bean id= "Persondao" class= "Cn.soldier.dao.impl.PersonDaoBean" ></bean>
<bean id= "Personservice" class= "Cn.soldier.service.impl.PersonServiceBean" >
<constructor-arg index= "0" type= "Cn.soldier.dao.PersonDao" ref= "Persondao"/>
<constructor-arg index= "1" value= "uses the constructor method to inject the base type (String):" hehe "into the bean"/>
</bean>

--------------------------------------------------------------------------------------------------------------- -------
The second Kind


Inject using setter method
Personservicebean.class
1.personservicebean.class Component Definition Property getter Setter
Private Persondao Persondao;
Omit getter and setter
2. Methods for invoking objects
Persondao.xxxmethod ();
3. Configure Beans

<bean id= "Personservice" class= "Cn.soldier.service.impl.PersonServiceBean" >
<property name= "Persondao" ref= "PERSONDAOAA" ></property>
</bean>
<bean id= "PERSONDAOAA" class= "Cn.soldier.dao.impl.PersonDaoBean" ></bean>


3.1 Way Two: (using an internal bean, but the bean cannot be used for other filings)

<bean id= "Personservice" class= "Cn.soldier.service.impl.PersonServiceBean" >
<property name= "Persondao" >
<bean class= "Cn.soldier.dao.impl.PersonDaoBean"/>
</property>
</bean>

--inject the base type into the bean
1. Provide getter,setter
Personservicebean.clsss
private String name;
Omit getter and setter
Beans.xml
<bean id= "Personservice" class= "Cn.soldier.service.impl.PersonServiceBean" >
<property name= "name" value= "inject basic type (String):" hehe "into the bean" ></property>
</bean>

--inject the collection into the bean
Private set<string> sets = new Hashset<string> ();
Private list<string> lists = new arraylist<string> ();
Private Properties Properties = new properties ();
Private map<string, string> maps = new hashmap<string, string> ();
Omit getter and setter
<property name= "Sets" >
<set>
<value> Oh 1-set</value>
<value> Oh 2-set</value>
<value> Oh 3-set</value>
<value> Oh 4-set</value>
</set>
</property>
<property name= "lists" >
<list>
<value> Oh 1-list</value>
<value> Oh 2-list</value>
<value> Oh 3-list</value>
<value> Oh 4-list</value>
</list>
</property>
<property name= "Properties" >
<props>
<prop key= "Key1" > ha-ha 1-properties</prop>
<prop key= "Key2" > ha-ha 2-properties</prop>
<prop key= "Key3" > ha-ha 3-properties</prop>
<prop key= "Key4" > ha-ha 4-properties</prop>
</props>
</property>
<property name= "Maps" >

<map>
<entry key= "map-k-1" value= "Map-v-1"/>
<entry key= "map-k-2" value= "Map-v-2"/>
<entry key= "map-k-3" value= "map-v-3"/>
</map>
</property>
--------------------------------------------------------------------------------------------------------------- -------
Third use of the field method (annotations)
Injecting dependent objects

Injection-dependent objects can be manually assembled or automatically assembled, and manual assembly is recommended for practical use.
Because automatic assembly creates an unknown situation, developers cannot foresee final assembly results

1. Assembling dependent objects manually

In the Java code using [@Autowired], [@Resource] way to assemble, the difference between the two annotations is
@Autowired assemble by type by default
The @Resource is installed by default, and will not be used when a bean matching the name is found.

@Autowired annotation is the assembly of dependent objects by type, by default it requires that the dependent object must exist.
If a null value is allowed, you can set its Required property to false.
If you want to use assembly by name, you can use it in conjunction with [@Qualifier] annotations.
Examples are as follows:
@Autowired @Qualifier ["Persondaobean"]
Private Persondao Persondao;


1.beans.xml
<beans xmlns= "Http://www.springframework.org/schema/beans"
xmlns:xsi= "/http/ Www.w3.org/2001/XMLSchema-instance "
xmlns:context=" Http://www.springframework.org/schema/context "
xsi: schemalocation= "Http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/ Spring-beans-2.0.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema /context/spring-context-2.5.xsd "
<context:annotation-config/>
<bean id=" PersonDaoCC "class=" Cn.soldier.dao.impl.PersonDaoBean "></BEAN>

</beans>
Personservicebean.class
Using
@Resource (name = "PERSONDAOCC")
private Persondao PersonDao3;
or use
private Persondao PersonDao3;
@ Resource//Use the property of the field method to inject
public void Setpersondaocc (Persondao personDao3) {
This.persondao3 = PersonDao3;
}
or use
@Autowired (required=false) | @Qualifier ("PERSONDAOCC")
private Persondao PersonDao3;


2. Automatic assembly of dependent objects
1.bean.xml
<bean id= "Persondao" class= "Cn.soldier.dao.impl.PersonDaoBean"/>
<bean id= "Personservice" class= "Cn.soldier.service.impl.PersonServiceBean" autowire= "Bytype"/>
2.personservicebean.class
Private Persondao Persondao;
Omit setter
Persondao.add ();

The Autowire property is evaluated as follows:
Bytype Properties: Matching by type, you can find beans that match that type in the container based on the type of the property. If more than one is found, an exception will be thrown. If not found, then the property value is null.
ByName property: Assembled by name, you can find the bean in the container that is the same as the property name, based on the name of the property. If not found, then the property value is null.
Constructor properties: constructor is similar to Bytype, except that it applies constructor parameters. If no bean is found with the constructor parameter type, an exception will be thrown.
AutoDetect property: Use the Bean class's introspection mechanism (introspection) to decide whether to use constructor or Bytype to automate assembly,<!--If a default constructor is found, then the Bytype method is used- >

[4] management by incorporating components into the spring container in the Classpath automatic scanning mode

SPRING2.5 introduces an automatic scanning mechanism that looks for classes labeled @Component @Service @Controller @Repository annotations in the classpath, and incorporates these classes into spring
Managed in the container.

@Service for marking business layer components
@Controller used to label control-layer components (such as Struts action)
@Repository used to label data access Components that DAO layer
@Component refer to components, which can be annotated when the component is poorly categorized

1.beans.xml
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "Http://www.springframework.org/schema/context"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-2.5.xsd ">

<context:component-scan base-package= "Cn.soldier"/>
<!--all classes under scan packages and sub-packages. It also contains the field processor <context:annotation-config/>-

</beans>

@Service ("xxxxx")//default is the simple name of the class, which is manually modified to xxxxx
public class Personservicebean implements Personservice {
...
}
@Service @Scope ("prototype")//scope changed to prototype
public class Personservicebean implements Personservice {
...
}

@Service
public class Personservicebean implements Personservice {
@PostConstruct
public void init () {
System.out.println ("Inint");//Initialize Start
}
@PreDestroy
public void Distory () {
System.out.println ("Distory");//Logoff is startup
}
}

[5] Aop
Spring provides two facets-oriented usage, and we can choose one of them in the actual work.
1. AOP development based on the XML configuration method

2. Development of AOP based on annotation method

1.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" xmlns:context= "Http://www.springframework.org/schema/context"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"

Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-2.5.xsd
Http://www.springframework.org/schema/aop
Http://www.springframework.org/schema/aop/spring-aop-2.5.xsd ">
<!--managed by incorporating components into the spring container in the Classpath auto-scan mode
<context:component-scan base-package= "Cn.soldier"/>
<aop:aspectj-autoproxy/><!--enable support for @aspertj annotations--
</beans>

2. Define a pointcut, define a notification,
Myinterceptor.class
@Aspect
@Component
public class Myinterceptor {
@Pointcut ("Execution (* cn.soldier.service.impl.personservicebean.* (..))")
Defining pointcuts
private void Anymethod () {
System.out.println ("Myinterceptor.anymethod ()");
}

Defining a pre-notification
@Before ("Anymethod () && args (name)")
public void Doaccesscheck (String name) {
System.out.println ("Myinterceptor.doaccesscheck () Pre-notification");
System.out.println ("Print pass in Parameter" + name);
}

Define a POST notification
@AfterReturning (pointcut = "Anymethod ()", returning = "Result")
public void Doreturncheek (String result) {
System.out.println ("Myinterceptor.doreturncheek () post notification");
SYSTEM.OUT.PRINTLN ("Return result after printing execution function" + result);
}

Defining exception Notifications
@AfterThrowing (pointcut = "Anymethod ()", throwing = "ex")
public void Doexceptionaction (Exception ex) {
System.out
. println ("myinterceptor.doexceptionaction () doexceptionaction");
Ex.printstacktrace ();
}

Defining final Notifications
@After ("Anymethod ()")
public void Doreleaseaction () {
System.out.println ("myinterceptor.doreleaseaction () Final Notice");
}

Surround Notifications
@Around ("Anymethod ()")
Public Object dobasicprofiling (Proceedingjoinpoint pjp) throws Throwable {
if () {//Determine if user has permission
System.out.println ("-Surround notification-execution start--");
Object result = Pjp.proceed ();
System.out.println ("-surround notification-execution end--");
// }
return result;
}
}

[6] Spring integrated JDBC
1. Add a Jar file
Using spring requires
Sring.jar
Commons-loggin.jar
If you use an AOP component
Need Aspectjweaver.jar
Aspectjrt.jar
If you are using jsr-250 annotations
Need
Commom-annotations.jar
Working with data sources
Need
Commons-pool.jar
Commons-dbcp.jar
Using a MySQL database requires
Mysql-connector-java-5.1.7-bin.jar


2. Configure the data source
<!--Import external properties-->
<context:property-placeholder location= "classpath: Jdbc.properties "/>
<bean id=" DataSource "class=" Org.apache.commons.dbcp.BasicDataSource "
Destroy-method= "Close",
<property name= "Driverclassname" value= "${driverclassname}"/>
< Property name= "url" value= "${url}"/>
<property name= "username" value= "${username}"/>
<property Name= "Password" value= "${password}"/>
<!--initial value when connection pooling starts-->
<property name= "initialsize" value= "${ InitialSize} "/>
<!--The maximum value of the connection pool-->
<property name=" maxactive "value=" ${maxactive} "/>
<!-- Maximum idle value, when a peak time passes, the connection pool can slowly release the connection that has not been used to slow down to maxidle until-->
<property name= "Maxidle" value= "${maxidle}"/
<!--minimum idle value, the connection pool will request some connection when the Shao threshold is idle, lest the flood peak come too late to apply for-->
<property name= "Minidle" value= "${minidle} "/>
</bean>


3. Configure Transaction Management
<bean id= "Txmanager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name= "DataSource" ref= "DataSource"/>
</bean>

4. Note Enable transactional components
Method One: Annotation method
1. Enable support for @transaction annotations
1.1 Adding a TX namespace
<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "Http://www.springframework.org/schema/context"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:tx= "Http://www.springframework.org/schema/tx"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
Http://www.springframework.org/schema/tx
Http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-2.5.xsd
Http://www.springframework.org/schema/aop
Http://www.springframework.org/schema/aop/spring-aop-2.5.xsd ">
1.2 Enabling support for @transaction annotations
<!--enable support for @transaction annotations--->
<tx:annotation-driven transaction-manager= "Txmanager"/>


[6] Spring uses annotations to manage transactions

@Transactional (Rollbackfor=exception.class) rollback
@Transactional (Norollbackfor=runtimeexception.class) does not roll back
public void Delete (Integer PersonID) throws exception{
Jdbctemplate.update (//
"Delete from person where id=?" //
, new object[] {PersonID}//
, new int[] {Java.sql.Types.INTEGER});
throw new RuntimeException ("Run-time accident");
If the throw is a run-time unexpected, the transaction is rolled back. Because RuntimeException is a unchecked anomaly,
If it is a checked exception, the transaction will not be rolled back
}
Propagation properties of a transaction
@Transactional (propagation = propagation.not_supported)//Specifies that transaction behavior is not turned on
Public person Getperson (Integer PersonID) {
return (person) jdbctemplate.queryforobject (//
"SELECT * from the person where id=?" //
, new object[] {PersonID}//
, new int[] {Java.sql.Types.INTEGER}//
, new Personrowmapper ());
}
@Transactional (propagation=propagation.required)//default behavior, which means that the method needs to run in a transaction.
public void Save (person person) {
Jdbctemplate.update (//
Insert INTO (name) values (?) //
, new object[] {person.getname ()}//
, new int[] {Java.sql.Types.VARCHAR});
}
Transaction isolation level of the database

The database system provides four levels of transaction isolation for users to choose from.

Read uncommited reading uncommitted data (dirty reads, non-repeatable reads, and Phantom reads)
Read commited reads the submitted data (non-repeatable read and Phantom reads occur)
REPEATABLE READ REPEATABLE READ (phantom read occurs)
Serializble serialization

Dirty read: Is the update data that a transaction reads to another transaction for the commit.
Non-repeatable READ: The result of reading the same data multiple times in a transaction is different. In other words, a subsequent read can read the data submitted by another transaction.
REPEATABLE READ: In the same transaction, when the data is read multiple times, the data can be guaranteed to read the same, that is, subsequent reads cannot be read to another transaction committed update data.
Phantom READ: Is the insert data that a transaction reads to another transaction that has been committed.

Spring Learning Notes

Related Article

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.