Configuration of xml
Create xml file in src directory, named custom
Add code to xml
<?xml version="1.0" encoding="UTF-8"?> <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="http://www.springframework.org/schema/beans" 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"> <!--Configure one bean Equivalent to creating one UserService object--> <bean id="userService" class="cn.itcast.service.UserServiceImpl"> <!--adopt IcO(Dependent Injection) Injection--> <property name="name" value="zhangsan"></property> </bean> </beans>
Use of IoC (case)
Create IUserService Interface
public interface IUserService { public void add(); }
Create UserServiceImpl implementation class
public class UserServiceImpl implements IUserService { @Override public void add() { System.out.println("Create User..."); } }
Add in beans
<bean id="userService" class="com.gxq.service.UserServiceImpl"></bean>
Create test class Lesson and add
@Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); IUserService service= (IUserService) context.getBean("userService"); service.add(); }
Getting bean s from.mxl
The first is obtained from the ClassPathXmlApplicationContext (commonly used)
ApplicationContext context = new ClassPathXmlApplicationContext("xml file name); UserService userService = (Strong to xxx object) context.getBean("bean In id value"); userService.add();//Call Method
The second is obtained from the real directory of the xml file
ApplicationContext context = new FileSystemXmlApplicationContext("D:\\spring\\day01_spring1\\src\\beans.xml"); UserService userService = (Strong to xxx object) context.getBean("bean In id value"); userService.add();//Call Method
Third, use BeanFactory to get (outdated)
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("D:\\spring\\day01_spring1\\src\\beans.xml")); UserService userService = (UserService) factory.getBean("userService");userService.add();
Construction method default preferred execution
How Spring creates objects internally
- Parse the xml file to get the class name, id, attributes
- Create objects with types by reflection
- Assigning values to created objects
Three ways to assemble bean s
First: the new implementation class
<bean id="userService1" class="cn.itcast.service.UserServiceImpl"></bean>
Second way: through the static factory method
//Method in Static Factory public static UserService createUserSerice(){ return new UserServiceImpl(); } <!--xml In bean--> <bean id="userService2" class="Location of Static Factory" factory-method="createUserSerice"></bean> //Static method call twice
Third way: through the instance factory method
//Method in Instance Factory public UserService createUserSerice(){ return new UserServiceImpl(); } <!--xml In bean--> <bean id="factory2" class="Location of instance factory"></bean> <bean id="userService3" factory-bean="factory2" factory-method="createUserSerice"></bean> //Static method call three times
DI Dependent Injection
<bean id="userService1" class="cn.itcast.service.UserServiceImpl"> <property name="name" value="zs"></property>//Dependent Injection </bean>
Scope of bean s
Setting method: scope property
<bean id="userService1" class="cn.itcast.service.UserServiceImpl" scope="prototype"></bean>
Singleton: There is only one Bean instance in the Spring IoC container, Bean exists as a singleton with the same memory address; default
prototype: Each time a Bean is called from a container, a new instance is returned, that is, each time getBean() is called, it is equivalent to executing a new XxBean (), with a different memory address
Life cycle of bean s
[External chain picture transfer failed (img-M4XuH5Ny-1564896745849)(en-resource://database/888:1)]
Life Cycle Diagram Interpretation
1.instantiate bean object instantiation
2.populate properties encapsulation properties
3. If Bean implements BeanNameAware to execute setBeanName: Name of the created object
4. If Bean implements BeanFactoryAware to execute setBeanFactory, get the Spring container: Bean Factory
5. Execute postProcessBeforeInitialization if there is a class implementing BeanPostProcessor (PreprocessBean)
6. If Bean implements InitializingBean to execute afterPropertiesSet: Attribute assignment complete
7. Invoke the specified initialization method init: Customize the initialization method
8. Execute postProcessAfterInitialization if there is a class implementing Bean PostProcessor
Perform business processing
9. If the Bean implements DisposableBean to execute destroy: destroy the bean object
10. Call the specified destroy method customerDestroy
11. Destroy the bean object (close the container):service.getClass().getMethod("close"). invoke(context);
Assigning values to attributes of objects
Method 1: Inject by a construction method (provided there is a construction method in Student)
<bean id="stu" class="cn.itcast.model.Student"> <constructor-arg name="username" value="zhangsanz"></constructor-arg> <constructor-arg name="password" value="123"></constructor-arg> </bean>
Method 2: Inject by Index and Type
<bean id="stu" class="cn.itcast.model.Student"> <constructor-arg index="0" value="zangsan" type="java.lang.String"></constructor-arg> <constructor-arg index="1" value="20" type="int"></constructor-arg> </bean>
Method 3: Injection by set method
<bean id="stu" class="cn.itcast.model.Student"> <property name="username" value="zhangsan"></property> <property name="password" value="zhangsan"></property> <property name="age" value="20"></property> </bean>
Method 4: p namespace injection (dependent on set method)
- Add to Head
xmlns:p="http://www.springframework.org/schema/p"
- injection
<bean id="stu" class="cn.itcast.model.Student" p:username="zs" p:password="ls" p:age="23"></bean>
spEL
Format:
Type:
#{123}, #{'jack'}: numbers, strings
#{beanId}: Another bean reference
#{beanId.propName}: Operational data
#{beanId.toString()}: Execution method
#{T (class). Field|Method}: Static method or field
Benefit: Method can be invoked
For example: <property name="name" value="#{'zhangsan'.toUpperCase()}"></property>
<property name="pi" value="#{T(java.lang.Math).PI}"></property>
Injection of collections
<-- list Injection --> <bean id="programmer" class="cn.itcast.model.Programmer"> <property name="cars"> <list> <value>Neck</value> <value>Cadillac</value> </list> </property> <-- set Injection --> <property name="pats"> <set> <value>dudou</value> <value>kity</value> </set> </property> <-- map --> <property name="house"> <map> <entry key="Shandong" value="Biguiyuan"></entry> <entry key="Beijing" value="Courtyard Dwellings"></entry> </map> </property> <-- Properties --> <property name="mysqlInfos"> <props> <prop key="url">mysql:jdbc://localhost:3306/pos</prop> <prop key="root">root</prop> <prop key="password">123456</prop> </props> </property> </bean>
Use of Notes
-
@Repository("name"):dao layer
-
@Service("name"):service layer
-
@Controller("name"):web layer
-
@Autowired: Auto type injection
-
@Qualifier("name"): Specify the id name for the auto-injection
-
@Resource("Name")
-
@ PostConstruct custom initialization method
-
@ PreDestroy custom destruction method
Add @Component("id") at the beginning of the class where you want to create the object
Add <to XMLContext:annotation-config/>
<context:component-scan base-package="cn.itcast"/>
When creating objects:
ApplicationContext context = new ClassPathXmlApplicationContext("xxxx.xml"); UserService service = (UserService) context.getBean("id"); //Use when IDS exist UserService service = (UserService) context.getBean(Implementation Class Name.class);
AOP
JDK Dynamic Proxy
Must be an implementation class of inherited interface to use AOP
cglib enhanced byte code
Implementation and generic classes that can be used to inherit interfaces
AOP Semi-automatic Programming
Import AOP Federation jar package:com.springsource.org.aopalliance-1.0.0
AOPjar package: spring-aop-3.2.10.RELEASE
Target class interface
public interface IUserService { public void add(); }
Target Class Implementation Class
public class UserServiceImpl implements IUserService { @Override public void add() { System.out.println("Create User"+name); } }
Test Class
public class Lessin07 { @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans7.xml"); IUserService service = (IUserService) context.getBean("sevriceProxy"); service.add(); } }
MyAspect Face Class
public class MyAspect implements MethodInterceptor { @Override public Object invoke(MethodInvocation mi) throws Throwable { //Interception Method) System.out.println("Open Transaction"); //Release Object retObj = mi.proceed(); System.out.println("intercept...."); System.out.println("Submit Transaction"); return retObj; } }
xml file
<?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:p="http://www.springframework.org/schema/p" 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"> <!--To configure userservice--> <bean id="userService" class="com.gxq.service.UserServiceImpl"></bean> <!--Configure Face Class--> <bean id="myAspect" class="com.gxq.service.MyAspect"></bean> <!--Configure Proxy Objects--> <bean id="sevriceProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <!--Interface--> <property name="interfaces" value="com.gxq.service.IUserService"/> <!--Target object--> <property name="target" ref="userService"></property> <!--Face class--> <property name="interceptorNames" value="myAspect"></property> </bean> </beans>
AOP Automatic Programming
ImportCom.springsource.org.Aspectj.weaver-1.6.8.RELEASE dependent jar package
Add in xml header
xmlns:aop="http://www.springframework.org/schema/aop //stayXsi:schemaLocationin http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
<bean id="userService" class="cn.itcast.service.UserServiceImpl"></bean> <!-- Configure Face Class Objects--> <bean id="myAspect" class="cn.itcast.service.MyAspect2"></bean> <!--Automatic AOP Configuration 1. Configure aop constraints in bean s 2. ConfigurationAop:configContent, combining entry point with notification proxy-target-class: Use cglib to implement proxy expression: *arbitrary execution(*)com.gyf.service*. * (.): Return value --> Package name --> Class name method name parameter <aop:config proxy-target-class="true"> <!--Start Point: expression:expression Each service's method is preceded by open and end transactions AOP: For Transaction Configuration &Logging --> <aop:pointcut id="myPointcut" expression="execution (* cn.itcast.service.UserServiceImpl.deleteUser())"/> <!--Notify associated entry point-->. <aop:advisor advice-ref="myAspect" pointcut-ref="myPointcut" ></aop:advisor> </aop:config>·
AspectJ
Import jar package: spring-aspects-3.2.10.RELEASE
Add code to xml
<!--To configure userservice--> <bean id="userService" class="com.gxq.service.UserServiceImpl"></bean> <!--Configure Face Class--> <bean id="myAspect3" class="com.gxq.aspect.MyAspect3"></bean> <!--To configure AOP--> <aop:config> <!--aop Specify Face--> <aop:aspect ref="myAspect3"> <!--Configure entry points--> <aop:pointcut id="myPointcut" expression="execution(* com.gxq.service.UserServiceImpl.*(..))"/> <!--Configure Pre-Notification--> <!--<aop:before method="myBefore" pointcut-ref="myPointcut"/>--> <!--Configure Post Notification--> <!--<aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"/>--> <!--Configure surround notifications--> <aop:around method="myAround" pointcut-ref="myPointcut"/> </aop:aspect> </aop:config>
Face class:
public class MyAspect3 { //Front public void myBefore(){ System.out.println("Before advice"); } //Rear //If the service has a return value, add the Object retValue parameter and the returning="retValue" attribute to the xml public void myAfterReturning(){ System.out.println("after returning advise"); } //surround public Object myAround(ProceedingJoinPoint pjp) throws Throwable { System.out.println("Around Advice"); System.out.println("Before advice"); //* Release * Object retObj = pjp.proceed(); System.out.println("after returning advise"); return retObj; } }
Notes for AspectJ
Add: @Component and @Aspect annotations to the facet class
Add: @Service("id") comment to service class
Code in xml file:
<context:component-scan base-package="com.gxq"/> <aop:aspectj-autoproxy/> <aop:config> //The ref value is lowercase for the face class name <aop:aspect ref="myAspect"></aop:aspect> </aop:config>
Code in test class:
ApplicationContext context = new ClassPathXmlApplicationContext("xml file name"); IUserService service = (IUserService) context.getBean("serviceID name"); //Call Method service.add(1);
@Aspect declares facets, decorates the facet class, and is notified.
notice
@Before Prefix
@AfterReturning Post
@Around Surround
@AfterThrowing threw an exception
@After Final
breakthrough point
@PointCut, decorate method private void xxx(){} and get entry point references through Method Name
Database Operation
c3p0 and JdbcTemplate
Import package:com.springsource.org.apache.commons.dbcp-1.2.2.osgi
com.springsource.org.apache.commons.pool-1.5.3
mysql-connector-java-5.1.37-bin
spring-jdbc-3.2.10.RELEASE
spring-tx-3.2.10.RELEASE
UserDaoImpl inherits IUserDao
public class UserDaoImpl implements IUserDao { JdbcTemplate jdbcTemplate = new JdbcTemplate(); public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public void add(User user) { System.out.println("userDao Add User"+user); jdbcTemplate.update("insert into t_user (username,password) values (?,?)",user.getUsername(),user.getPassword()); } }
Add in dao
public class UserDaoImpl implements IUserDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public void add(User user) { jdbcTemplate.update("insert t_user(username,password) values (?,?)",user.getUsername(),user.getPassword()); }
Configuration file for c3p0.properties
driverClass=com.mysql.jdbc.Driverjdbc Url=jdbc:mysql:///spring_day04 user=root password=123456
Add in xml
<!--JdbcTemplate To configure DataSource--> <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///spring_day04"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> --> <!-- c3p0 To configure DataSource--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="user" value="${user}"/> <property name="password" value="${password}/> </bean> <!-- To configure jdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- To configure dao --> <bean id="userDao" class="com.gxq.dao.UserDaoImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean>
Test Class
public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans05.xml"); IUserDao userDao = (IUserDao) context.getBean("userDao"); User user = new User(); user.setUsername("zzm"); user.setPassword("123"); userDao.add(user); }
Transaction Operation
Transaction Configuration for AOP
<!--jdbc To configure--> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="user" value="${user}"/> <property name="password" value="${password}"/> </bean> <bean id="accountDao" class="com.gxq.dao.Impl.AccoutDaoImpl"> <property name="dataSource" ref="dataSource"></property> </bean> <!--Configure Transaction Manager--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--To configure DataSource--> <property name="dataSource" ref="dataSource"></property> </bean> <!--To configure service--> <bean id="accountService" class="com.gxq.service.AccountService"> <property name="accountDao" ref="accountDao"></property> </bean> <!--Configure Notification Transaction Manager--> <tx:advice id="txAdvice" transaction-manager="txManager"> <!--Transaction details: Dissemination Behavior Isolation Level--> <tx:attributes> <tx:method name="service Method name in" propagation="REQUIRED" isolation="DEFAULT"/> . . Can be multiple . </tx:attributes> </tx:advice> <!--Start Point Link Notification Transaction Manager--> <aop:config> <aop:pointcut id="myPointCut" expression="execution(* com.gxq.service..*.*(..))"> </aop:pointcut> <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointCut"> </aop:advisor> </aop:config>
Transaction configuration via annotations
In xml
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="user" value="${user}"/> <property name="password" value="${password}"/> </bean> <bean id="accountDao" class="com.gxq.dao.Impl.AccoutDaoImpl"> <property name="dataSource" ref="dataSource"></property> </bean> <!--To configure service--> <bean id="accountService" class="com.gxq.service.AccountService"> <property name="accountDao" ref="accountDao"></property> </bean> <!--Configure Transaction Manager--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--To configure DataSource--> <property name="dataSource" ref="dataSource"></property> </bean> <!--Start Point Link Notification Transaction Manager--> <tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
Add the @Transactional annotation to the service
- Attributes can be written in subsequent () or default if not written
- Scope by location, write on class name, all methods of the entire class work; write on method name, only this method works
Integration of spring Servlet s
Create in src directoryApplicationContext.xml
And add the configuration code for spring
<?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:p="http://www.springframework.org/schema/p" 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.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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> </beans>
stayWeb.xmlAdd in
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
servlet
//LoadApplicationContext.xmlfile ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); //Create classes from bean s userService = (IUserService) context.getBean("userService"); //Call Method userService.add(username);