spring is actually a container, and IOC is one of them to collect our objects
IOC create object
- User
public class User { private String name; public User(){ System.out.println("User Nonparametric structure of"); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
- applicatonContext.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.xsd"> <import resource="beans.xml"></import> <alias name="hello" alias="hello1"></alias> <bean id="hello" class="com.liu.pojo.Hello" name = "hello2,hello3 hello4;hello5"> <property name="str" value="Spring"/> </bean> </beans>
- test
public class MyTest { public static void main(String[] args) { //Get the context object of Spring ApplicationContext Context = new ClassPathXmlApplicationContext("applicatonContext.xml"); //Our objects are now managed in Spring. If we want to use them, we can take them out directly Hello hello = (Hello) Context.getBean("hello"); // Hello hello = Context.getBean("hello",Hello.class); You don't have to turn every time System.out.println(hello); } }
- Use Spring to create objects. In Spring, these objects are called beans, and the object field is the property attribute
- < bean id = "hello" class = "com. Liu. POJO. Hello" > < / bean > is equivalent to creating an object (new Hello() parameterless construction)
- < property name = "name" value = "ljy" > < / property > is equivalent to user.set(ljy)
- id = variable name (the unique identifier of the bean, that is, the object name we learned)
- class = new object (fully qualified name corresponding to the object: package name + class name)
- Property is equivalent to setting a value for a property in an object
- Alias aliases the variable name. Name in the bean is also an alias, and name is more advanced. You can take multiple aliases at the same time. Spaces, commas and semicolons can be separated
- < import resource = "beans. XML" > < / import > import other configuration files
Summary: when the configuration file is loaded, the objects managed in the container have been initialized
Dependency injection DI
Injection is mainly to inject attributes into objects, that is, assign values to attributes, that is, the setxxx() method, which is now handed over to the spring container
Constructor Injection
- Parametric structure
public User(String name){ this.name = name; }
- Three types of applicationcontext.xml
<!--First subscript assignment --> <bean id="user" class="com.liu.pojo.User"> <constructor-arg index="0" value="Liu Jianyu"></constructor-arg> </bean> <!--The second method of creating by type is not recommended--> <bean id="user" class="com.liu.pojo.User"> <constructor-arg type="java.lang.String" value="liujianyu"></constructor-arg> </bean> <!--The third method is set directly by parameter name--> <bean id="user" class="com.liu.pojo.User"> <constructor-arg name = "name" value="Liu Jian"></constructor-arg> </bean>
- Parameterless construction, using the set method
public User(){ System.out.println("User Nonparametric structure of"); }
- applicatonContext.xml
<!--Equivalent to creating an object (parameterless construction)--> <bean id="user1" class="com.liu.pojo.User"></bean> <bean id="user2" class="com.liu.pojo.User" > <property name="name" value="123"></property> </bean> <bean id="user" class="com.liu.pojo.User" name="user3,user4 user5;user6"> <property name="name" value="ljy"></property> </bean> <!--Alias,If an alias is added, we can also use the alias to get this object--> <alias name="user" alias="user7"></alias>
- Note that test outputs three parameterless constructs
public class MyTest { public static void main(String[] args) { //User user = new User(); //spring containers are similar to matchmaking ApplicationContext context = new ClassPathXmlApplicationContext("applicatonContext.xml"); User user = (User) context.getBean("user"); } } /* User Nonparametric structure of User Nonparametric structure of User Nonparametric structure of name=ljy */
set injection
- Student
public class Student { private String name; private Address address; private String[] books; private List<String> hobby; private Map<String,String> card; private Set<String> games; private String wife; private Properties info; }
- Address
public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
- applicatonContext.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.xsd"> <bean id="Address" class="com.liu.pojo.Address"> <property name="address" value="Chengdu"></property> </bean> <bean id="student" class="com.liu.pojo.Student"> <!--First, normal value injection, value--> <property name="name" value="ljy"></property> <!--Second, Bean Injection, ref--> <property name="address" ref="Address"></property> <!--Third, arrays, value--> <property name="books"> <array> <value>The Dream of Red Mansion</value> <value>Water Margin</value> <value>Romance of the Three Kingdoms</value> </array> </property> <!--list injection--> <property name="hobby"> <list> <value>listen to the music</value> <value>Knock code</value> <value>watch movie</value> </list> </property> <!--Map injection--> <property name="card"> <map> <entry key="ID" value="1234"/> <entry key="bank card" value="1212"/> </map> </property> <!--Set injection--> <property name="games"> <set> <value>LOL</value> <value>CS</value> <value>CF</value> </set> </property> <!--null injection--> <property name="wife"> <value>null</value> </property> <!--Properties--> <property name="info"> <props> <prop key="Student number">20190525</prop> <prop key="Gender">male</prop> </props> </property> </bean> </beans>
- test
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicatonContext.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.toString()); /* Student{name='ljy', address=Address{address='Chengdu '}, books=[Dream of Red Mansions, outlaws of the marsh, romance of the Three Kingdoms], hobby=[Listen to songs, type codes, watch movies], card={ID card = 1234, bank card = 1212}, games=[LOL, CS, CF], wife='null', info={Student number = 20190525, gender = male}} */ } }
Automatic assembly of Bean
Using Autowired, we don't need to write the set method. The precondition is that your auto assembled attribute is in the IOC(Spring) container, which also reduces our new steps
- People,Cat,Dog
public class People { //If the displayed defined Autowired property is false, it indicates that the object can be null, otherwise it is not allowed to be empty @Autowired(required = false) @Qualifier(value = "cat") // private Cat cat; @Autowired @Qualifier(value = "dog") private Dog dog; private String name; public Cat getCat() { return cat; } // If Autowired is used, there is no need to write the set method /*public void setCat(Cat cat) { this.cat = cat; }*/ public Dog getDog() { return dog; } /*public void setDog(Dog dog) { this.dog = dog; }*/ public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Dog { public void shout() { System.out.println("wang~"); } } public class Cat { public void shout() { System.out.println("miao~"); } }
- applicatonContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--Enable annotation support, that is, support Autowired--> <context:annotation-config/> <bean id="cat1" class="com.liu.pojo.Cat"></bean> <bean id="cat2" class="com.liu.pojo.Cat"></bean> <bean id="dog1" class="com.liu.pojo.Dog"></bean> <bean id="dog2" class="com.liu.pojo.Dog"></bean> <bean id="people" class="com.liu.pojo.People"> <property name="name" value="Xiao Liu"></property> <!--Because here Cat,Dog Used Autowired Automatic injection, so there is no need to write dog, cat If you write it, you will report an error because there is no more set method--> </bean> </beans>
- test
public class MyTest { @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); People people = context.getBean("people", People.class); people.getDog().shout(); people.getCat().shout(); System.out.println(people.getCat()); System.out.println(people.getDog()); System.out.println(people.getName()); System.out.println(people); } } /* wang~ miao~ com.liu.pojo.Cat@5a4aa2f2 com.liu.pojo.Dog@6591f517 Xiao Liu People{cat=com.liu.pojo.Cat@5a4aa2f2, dog=com.liu.pojo.Dog@6591f517, name='Xiao Liu '} */
- byName: it will be automatically searched in the container context, and the bean id must be unique
- byType: bean s with the same attribute type will be automatically found in the container context! The type must be globally unique, that is, the class must be unique, and the id can be omitted
@Autowired
- @Autowired matches the type (i.e. byType) first. If it repeats, look for beanid. If beanid and class definition variable names (cat,dog) are different, you can use @ Qualifier
@Autowired(required = false) @Qualifier(value = "cat1") private Cat cat; @Autowired @Qualifier(value = "dog1") private Dog dog; // Because there is no beanid with the same class definition variable name (cat,dog), you should use Qualifier to specify it. <bean id="cat1" class="com.liu.pojo.Cat"></bean> <bean id="cat2" class="com.liu.pojo.Cat"></bean> <bean id="dog1" class="com.liu.pojo.Dog"></bean> <bean id="dog2" class="com.liu.pojo.Dog"></bean>
@Resource
- @The Resource annotation matches beanid(byName) first and then the type. Contrary to @ Autowired, when beanid and attribute type are not available, the name tag can also be used to uniquely identify the bean injection
public class People { @Resource(name="cat2") private Cat cat; @Resource() private Dog dog; } // That is, cat is not equal to cat2, and then match the type to find that the type is unique, so it will be locked to cat2. If cat1 is added, it will not be unique when matching the type, so you must add name to lock, otherwise an error will be reported // <bean id="cat1" class="com.liu.pojo.Cat"></bean> <bean id="cat2" class="com.liu.pojo.Cat"></bean> <bean id="dog1" class="com.liu.pojo.Dog"></bean> <bean id="dog2" class="com.liu.pojo.Dog"></bean>
@Difference between Resource and @ Autowired:
-
They are used for automatic assembly and can be placed in our attribute field
-
@Autowired is implemented by byType, and the object must have [common]
-
@Resource is implemented by byName by default. If the name cannot be found, it is implemented by byType!
-
@Resource is equivalent to the combination of @ Autowired and @ Qualifier
summary
-
Using @ Autowired means that we get our objects directly from the container. We don't need to write the set method to set, and we also reduce our new steps
-
Enable annotation support < context: annotation config / > before using
Annotation development
Add annotation support to the context constraints that need to be imported when using annotations
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd <!--Specify the package to be scanned, and the annotations under the package will take effect automatically--> <context:component-scan base-package="com.liu"/> <!--Enable annotation support--> <context:annotation-config/> </bean
- @Component
@Component //Equivalent to < bean id = "user" class = "com. Liu. POJO. User" / > //@Component component @Scope("singleton") //Marked as singleton and prototype public class User { @Value("liujianyu") //Equivalent to < property name = "name" value = "liujianyu" > < / property > public String name; @Value("liujianyu2") public void setName(String name) { this.name = name; } }
- @Component has several derived annotations. In web development, we will layer according to mvc three-tier architecture
- dao[@Repository]
- service[@Service]
- controller[@Controller]
- These four functions are the same. They all represent registering a class in Spring and assembling beans
Java configuration xml
Now we will completely not apply the xml configuration of Spring, and leave it to Java!
- User
//The annotation here means that this class is taken over by Spring and registered in the container @Component public class User { private String name; public String getName() { return name; } @Value("liujianyu") public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
- @Configuration represents a configuration class, which is the same as beans.xml we saw earlier
@Configuration //This will also be managed by the Spring container and registered in the container, because it is originally a @ Component @ComponentScan("com.liu.pojo")//Scan package @Import(MyConfig2.class)//Introduce other configuration classes public class MyConfig { @Bean //Registering a bean is equivalent to a bean tag we wrote earlier //The name of this method is equivalent to the id attribute in the bean tag //The return value of this method is equivalent to the class attribute in the bean tag public User getUser() { System.out.println("This method was executed================="); return new User();//Is to return the object to be injected into the bean! } }
- test
public class MyTest { public static void main(String[] args) { //If the configuration class method is completely used, we can only obtain the container through the AnnotationConfig context and load it through the class object of the configuration class! ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); User getUser = (User) context.getBean("user"); // The reason why you can go to user here is @ Component, which goes to bean s in xml System.out.println(getUser.getName()); User user = context.getBean("getUser", User.class); //Take the method name. This is the bean that goes first, and then the new User(); System.out.println(user.getName()); System.out.println(user == getUser); } } /* This method was executed================= liujianyu This method was executed================= liujianyu false */
proxy pattern
Rent a house
- Static proxy
//Rent a house public interface Rent { public void rent(); } //landlord or landlady public class Host implements Rent { public void rent() { System.out.println("The landlord wants to rent the house"); } } //agent public class Proxy implements Rent { private Host host; public Proxy(Host host) { this.host = host; } public void rent() { seeHouse(); host.rent(); hetong(); fare(); } //House viewing public void seeHouse(){ System.out.println("The agent will show you the house"); } //sign a contract public void hetong(){ System.out.println("Sign a lease contract"); } //Intermediary fee public void fare(){ System.out.println("Intermediary fee"); } } //customer public class Client { public static void main(String[] args) { //The landlord wants to rent a house Host host = new Host(); //Agents and intermediaries help the landlord rent a house. However, the general agent role will have some ancillary operations! Proxy proxy = new Proxy(host); //You don't have to face the landlord, just find an intermediary to rent a house! proxy.rent(); /* The agent will show you the house The landlord wants to rent the house Sign a lease contract Intermediary fee */ } }
User management service
- Static proxy
public interface UserService { public void add(); public void delete(); public void update(); public void query(); } public class UserServiceImpl implements UserService { public void add() { System.out.println("Added a user"); } public void delete() { System.out.println("A user was deleted"); } public void update() { System.out.println("Modified a user"); } public void query() { System.out.println("A user was queried"); } //Changing the original business code is a big taboo in the company! So we need to use agents to expand functions } public class UserServiceProxy implements UserService{ private UserServiceImpl userService; public void setUserService(UserServiceImpl userService) { this.userService = userService; } public void add() { log("add"); userService.add(); } public void delete() { log("delete"); userService.delete(); } public void update() { log("update"); userService.update(); } public void query() { log("query"); userService.query(); } //Log method public void log(String msg){ System.out.println("[Debug]Used"+msg+"method"); } } public class Client { public static void main(String[] args) { UserServiceImpl userService = new UserServiceImpl(); UserServiceProxy proxy = new UserServiceProxy(); proxy.setUserService(userService); proxy.add(); /* [Debug]The add method is used Added a user */ } }
Rent a house
- Dynamic agent
//We will use this class to automatically generate proxy classes! public class ProxyInvocationHandler implements InvocationHandler { //Proxy interface private Rent rent; public void setRent(Rent rent) { this.rent = rent; } //Generated proxy class public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this ); } //Process the proxy instance and return the result public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //The essence of dynamic agent is to use reflection mechanism! seeHouse(); Object result = method.invoke(rent, args); fare(); return result; } public void seeHouse() { System.out.println("Show me the house"); } public void fare() { System.out.println("Intermediary fee"); } } public class Client { public static void main(String[] args) { //Real role Host host = new Host(); //Agent role: not now ProxyInvocationHandler pih = new ProxyInvocationHandler(); //Handle the interface object we want to call by calling the program processing role! pih.setRent(host); Rent proxy = (Rent) pih.getProxy();//The Proxy here is generated dynamically. We didn't write it proxy.rent(); /* Connected to the target VM, address: '127.0.0.1:50900', transport: 'socket' Show me the house The landlord wants to rent the house Intermediary fee Disconnected from the target VM, address: '127.0.0.1:50900', transport: 'socket' */ } }
User management service
- Dynamic agent
//We will use this class to automatically generate proxy classes! public class ProxyInvocationHandler implements InvocationHandler { //Proxied interface (real role) private Object target; public void setTarget(Object target) { this.target = target; } //Generated proxy class public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this ); } //Process the proxy instance and return the result public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //The essence of dynamic agent is to use reflection mechanism! log(method.getName());//Add log Object result = method.invoke(target, args); return result; } public void log(String msg) { System.out.println("Yes"+msg+"method"); } } public class Client{ public static void main(String[] args) { //Real role UserServiceImpl userService = new UserServiceImpl(); //Proxy role, does not exist ProxyInvocationHandler pih = new ProxyInvocationHandler(); pih.setTarget(userService);//Sets the object to proxy //Dynamically generate proxy classes UserService proxy = (UserService) pih.getProxy(); proxy.delete(); /* The delete method was executed A user was deleted */ } }
AOP
[key] to use AOP injection, you need to import a dependency package
<dependencies> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> </dependencies>
AOP adds new functions (agents) without changing the original code
- Service
public interface UserService { public void add(); public void delete(); public void update(); public void select(); } public class UserServiceImpl implements UserService{ public void add() { System.out.println("Add a method"); } public void delete() { System.out.println("Delete a method"); } public void update() { System.out.println("Modify a method"); } public void select() { System.out.println("Query a method"); } }
- test
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //Dynamic proxy, proxy interface: Note UserService userService = (UserService) context.getBean("userService"); userService.delete(); } }
- applicationContext.xml
- Method 1: use the native Spring API interface
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--register bean--> <bean id="userService" class="com.liu.service.UserServiceImpl"/> <bean id="log" class="com.liu.log.Log"/> <bean id="afterLog" class="com.liu.log.AfterLog"/> <!--to configure AOP:Import required AOP Constraints of--> <aop:config> <!--breakthrough point:expression:expression,execution(Location to execute! Modifier return value class name method name parameter)--> <aop:pointcut id="pointcut" expression="execution(* com.liu.service.UserServiceImpl.*(..))"/> <!--Perform surround enhancement!--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> </beans>
- log,afterlog
public class Log implements MethodBeforeAdvice { //Method: target object method to execute //Target: target object public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println(target.getClass().getName()+"of"+method.getName()+"Executed"); } } public class AfterLog implements AfterReturningAdvice { //returnValue: return value public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("Yes"+method.getName()+"Method to return the result by:"+returnValue+target.getClass().getName()); } } /* com.liu.service.UserServiceImpl The delete of was executed Delete a method The delete method is executed, and the returned result is nullcom.liu.service.UserServiceImpl */
- Method 2: user defined class
<!--......--> <bean id="diy" class="com.liu.diy.DiyPointCut"></bean> <aop:config> <!--Custom section ref:Class to reference--> <aop:aspect ref="diy"> <!--breakthrough point--> <aop:pointcut id="point" expression="execution(* com.liu.service.UserServiceImpl.*(..))"/> <!--notice--> <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config> <!--........-->
- Custom class DiyPointCut
public class DiyPointCut { public void before() { System.out.println("=============Before method execution============"); } public void after() { System.out.println("=============After method execution============"); } } /* =============Before method execution============ Delete a method =============After method execution============ */
- Method 3: using annotations
<!--......--> <bean id="annotationPointCut" class="com.liu.diy.AnnotationPointCut"/> <!--Enable annotation support! JDK(default proxy-target-class="false") cglib proxy-target-class="true"--> <aop:aspectj-autoproxy/> <!--........-->
- AnnotationPointCut
@Aspect//Label this class as a facet public class AnnotationPointCut { @Before("execution(* com.liu.service.UserServiceImpl.*(..))")//Define tangent point public void before() { System.out.println("=============Before method execution============"); } @After("execution(* com.liu.service.UserServiceImpl.*(..))") public void after() { System.out.println("=============After method execution============"); } //In surround enhancement, we can give a parameter representing the point where we want to get the processing pointcut @Around("execution(* com.liu.service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("=============Surround front============"); Object proceed = joinPoint.proceed();//Execution method System.out.println("=============After surround============"); Signature signature = joinPoint.getSignature();//Get signature System.out.println("signature"+signature); System.out.println(proceed); } } /* =============Surround front============ =============Before method execution============ Delete a method =============After method execution============ =============After surround============ signaturevoid com.liu.service.UserService.delete() null */
Integrate Myabatis
Import external properties resources
<!--Find us jdbc.properties--> <!--context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>-->
1. First kind
- UserMapper,UserMapperImpl,UserMapper.xml
public interface UserMapper { public List<User> getUser(); } public class UserMapperImpl implements UserMapper{ //All our operations are performed with sqlSession. Now we use SqlSessionTemplate private SqlSessionTemplate sqlSessionTemplate; public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } public List<User> getUser() { UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class); return mapper.getUser(); } } /* <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace=Bind a corresponding Dao/Mapper interface -- > <mapper namespace="com.liu.dao.UserMapper"> <select id="getUser" resultType="com.liu.pojo.User"> select * from mybatis.user; </select> </mapper */
- User
public class User { private int id; private String name; private String pwd; @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
- spring-dao.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.xsd"> <!--dataSource--> <!--DataSource:use Spring Data source replacement for Mybatis On the configuration of c3p0 dbcp druid We use it here Spring Provided JDBC org.springframework.jdbc.datasource--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!--a key--> <!--sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" > <property name="dataSource" ref="dataSource"></property> <!--binding Mybatis configuration file--> <!--It can be replaced here mybatis Contents in the configuration file <mappers> <mapper class="com.liu.dao.UserMapper"/> </mappers>--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="mapperLocations" value="classpath:com/liu/dao/UserMapper.xml"/> </bean> <!--sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--Only constructor injection can be used sqlSessionFactory,Because it doesn't set method--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!--userMapper--> <bean id="userMapper" class="com.liu.dao.UserMapperImpl"> <property name="sqlSessionTemplate" ref="sqlSession"></property> </bean> </beans>
- test
public class MyTest { public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapper bean = (UserMapper) context.getBean("userMapper"); List<User> user = bean.getUser(); for (User user1 : user) { System.out.println(user1); } }
2. Second
- UserMapperImpl2
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{ public List<User> getUser() { return getSqlSession().getMapper(UserMapper.class).getUser(); } }
- spring-dao.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.xsd"> <!--dataSource--> <!--DataSource:use Spring Data source replacement for Mybatis On the configuration of c3p0 dbcp druid We use it here Spring Provided JDBC org.springframework.jdbc.datasource--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!--a key--> <!--sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" > <property name="dataSource" ref="dataSource"></property> <!--binding Mybatis configuration file--> <!--It can be replaced here mybatis Contents in the configuration file <mappers> <mapper class="com.liu.dao.UserMapper"/> </mappers>--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="mapperLocations" value="classpath:com/liu/dao/UserMapper.xml"/> </bean> <!--userMapper2--> <bean id="userMapper2" class="com.liu.dao.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>
- test
public class MyTest { public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapper bean = (UserMapper) context.getBean("userMapper2"); List<User> user = bean.getUser(); for (User user1 : user) { System.out.println(user1); } }
spring configuration transaction
- applicationContext.xml
<!--Configure declarative transactions--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--combination AOP Implement transaction weaving--> <!--Configure transaction notifications--> <tx:advice id="XXX" transaction-manager="transactionManager"> <!--Configure transactions for those methods--> <!--Configure propagation properties of transactions--> <tx:attributes> <!--add Method configuration transaction--> <!-- <tx:method name="add" propagation="REQUIRED"/>--> <!--All methods--> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--Configure transaction entry--> <aop:config> <aop:pointcut id="xxx" expression="execution(* com.liu.dao.*.*(..))"/> <aop:advisor advice-ref="XXX" pointcut-ref="xxx"/> </aop:config>
- Make an error in the selectUser method in UserMapperImpl
public List<User> selectUser() { User user = new User(16, "AAA", "1234"); UserMapper mapper = getSqlSession().getMapper(UserMapper.class); mapper.deleteUser(15); // id primary key, and it already has No. 16, so an error will be reported, and the No. 15 deleted above will also be rolled back mapper.addUser(user); return mapper.selectUser(); }