cool hit counter SSH framework tour-spring (2)_Intefrankly

SSH framework tour-spring (2)


spring.jpg

1.bean management in Spring (annotation approach)


1.1 Creating objects using annotations

Spring Creating objects can be done using the configure xml Modalities of the document, You can also use annotations to create objects, It's even easier.。 This requires the introduction of a separate spring-aop of jar packet, Also to be found in configuration file Add the corresponding constraint in。

The sample code is as follows.

physical category

With the addition of the note.@Component(value="student") The annotation is equivalent to the previous use of the configuration <bean id="student" class="..."/>

There are four annotations for creating objects and three others @controller@Service@Repository all @Component derived annotations, which are functionally the same in that they both create objects. It is also clear from the name that the annotation has the purpose of delineating the class to be labeled.@Component for general entity classes.@controller for the Web layer.@Service for the business logic layer.@Repository for the data persistence layer.

Also, it is possible to use annotations to create whether an object is a single instance or multiple instances, simply by adding the class @Scope(value="prototype") It will be possible to create multiple instances of the object.

    package cc.wenshixin.entity;
    
    import org.springframework.stereotype.Component;
    
    @Component(value="student")
    public class Student {
        public void study(){
            System.out.println(" Learning in progress。。。");
        }
    }

configuration file

In the constraint configuration to add xmlns:context="http://www.springframework.org/schema/context" harmony http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

turn on Annotation scan, You can go to the package and scan the class、 approach、 Whether the property is annotated with。

<?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">
  
  <!--  turn on Annotation scan -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
</beans>

Test Method

package cc.wenshixin.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cc.wenshixin.entity.Student;

public class Test1 {
    
    @Test
    public void test01()
    {
         // 1. Load the spring configuration file and create objects based on the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
         //2. Get the object created by the annotation
        Student s = (Student) context.getBean("student");
        s.study();
    }
    
}

1.2 Using annotations to inject properties

establish service class harmony establish dao class, (located) at service obtained from dao class object of。

dao class

    package cc.wenshixin.dao;
    
    import org.springframework.stereotype.Repository;
    
    @Repository(value="dao")
    public class Dao {
        public void insert()
        {
            System.out.println("Insert data。。。");
        }
    }

service class

There are two ways to inject properties using annotations, and both ways do not require a set method in the dao.

package cc.wenshixin.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cc.wenshixin.dao.Dao;

@Service(value="service")
public class StudentService {
     // first way
    /*@Autowired
    private Dao dao;*/

     // Second way
     //name attribute value writes the value from the annotation when creating the dao object
    @Resource(name="dao")
    private Dao dao;
    
    public void add()
    {
        System.out.println(" Add Operation。。。");
        dao.insert();
    }
}

Test Method

package cc.wenshixin.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cc.wenshixin.entity.Student;
import cc.wenshixin.service.StudentService;

public class Test1 {
    
    @Test
    public void test01()
    {
         // 1. Load the spring configuration file and create objects based on the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
         //2. Get the object created by the annotation
        StudentService service = (StudentService) context.getBean("service");
        service.add();
    }
}

1.3 Mix of configuration and annotation approaches

In development, frequent xml configuration file way harmony Mix of annotation methods, Create objects using the configuration file, And property injection uses annotations。xml configure Clearly structured approach, The annotation approach facilitates property injection。

A comparison of bean management approaches in Spring

xml configuration

Annotation configuration

bean Definition

<bean id="" class=""/>

@Component,@Respository,@Service,@Controller

bean Name

Specify by id or name

@Component("student"), an odd onevalue happen to,value Can be omitted

bean injection

<property> Or byp namespace

@Autowired Injection by type,@Resource(name="")

The sample code is as follows.

dao class

package cc.wenshixin.dao;

public class TeacherDao {
    public void insert()
    {
        System.out.println(" Add Teacher。。。");
    }
}
package cc.wenshixin.dao;

public class StudentDao {
    public void insert()
    {
        System.out.println(" Add Student。。。");
    }
}

service class

package cc.wenshixin.service;

import javax.annotation.Resource;
import cc.wenshixin.dao.StudentDao;
import cc.wenshixin.dao.TeacherDao;

public class Service {
    @Resource(name="teacherDao")
    private TeacherDao teacherDao;
    @Resource(name="studentDao")
    private StudentDao studentDao;
    
    public void add()
    {
        System.out.println(" Add Operation。。。");
        teacherDao.insert();
        studentDao.insert();
    }
}

configuration 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: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">
  <!--  Configuration objects -->
  <bean id="service" class="cc.wenshixin.service.Service"></bean>
  <bean id="teacherDao" class="cc.wenshixin.dao.TeacherDao"></bean>
  <bean id="studentDao" class="cc.wenshixin.dao.StudentDao"></bean>
  
  <!--  turn on Annotation scan -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
</beans>

Test Method

package cc.wenshixin.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cc.wenshixin.service.Service;

public class Test1 {
    @Test
    public void test()
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Service service = (Service) context.getBean("service");
        service.add();
    }
}

2.AOP in Spring


2.1 AOP Complete Overview

AOP, the full name of Aspect Oriented Programming, cutter-oriented programming, has been mentioned in the Struts2 interceptor AOP, when the pre-compilation method and run-time dynamic proxy to achieve a unified maintenance of program functionality, extended functionality without modifying the source code, such as: permission checks, logging, performance monitoring, transaction control. AOP takes a horizontal extraction mechanism, replacing the duplicate code of traditional vertical inheritance systems. AOP solves some of the problems encountered in OOP (Object Oriented Programming) and is a continuation and extension of OOP.

The underlying dynamic proxy mechanism is of two kinds.

    1. There are interfaces, and the JDK's dynamic proxies, which generate proxies against classes that implement interfaces, generate interface implementation class objects.
    1. There is no interface, Cglib's dynamic proxy, which applies an underlying bytecode enhancement technique, generates subclass objects of the current class.

2.2 The underlying principles of AOP

Vertical extraction mechanism

Traditional way.png

Horizontal extraction mechanism

With interface.png

No interface.png

2.3 AOP operations related terms

  • Joinpoint (join point): methods inside a class that can be augmented, these methods are called are join points.
  • Pointcut( entry point): The entry point is the connection point to be intercepted。 There can be many methods inside a class that are enhanced, For example, the actual operations in, It just enhances the class inside the add approach harmony update approach, The actual enhancement is known as the entry point。
  • Advice (Notification/Augmentation): Notification is what is done after the Joinpoint is intercepted. Notification is further divided into Pre-notification, Post-notification, Exception Notification, Final Notification, Wrap-around Notification (the function to be accomplished by the cut). The logical feature to be enhanced is called an enhancement, for example, if you extend the logging feature, this logging feature becomes a notification or an enhancement. Pre-notification: executed before the enhanced method; post-notification: executed after the enhanced method; exception notification: when the method throws an exception; final notification: executed after the post; wrap-around notification: executed before and after the method.
  • Aspect (Tangent): a combination of entry point and notification (referral). The process of applying enhancements to the top of a specific method is called tangent. Putting enhancements to use in the entry point process.
  • Introduction: Introduction is a special kind of notification that can dynamically add methods or fields to a class at runtime without modifying the class code.
  • Target: the target object of the proxy (the class to be enhanced).
  • Weaving: is the process of applying enhancements to a target, that is, the process of applying advice to a target.
  • Proxy: A class is enhanced by AOP weaving into it to produce a resultant proxy class.

2.4 AOP practical operations

(located) at Spring conduct AOP operations use Aspectj realized,Aspectj not Spring part of, harmony Spring Use together AOP operations。 There are also two ways to implement AOP using Aspectj.

  • 1.Aspectj-based xml configuration
  • 2.Aspectj-based annotation approach

In addition to the above jar packages, you need to import the relevant jar packages for Aspectj Aspectjweaver.jar Download Addressaopalliance.jar which is available in the Struts2 lib.spring-aop.jarspring-aspects.jar

2.4.1 configuration file way

physical category

package cc.wenshixin.entity;

public class Student {
    public void study()
    {
        System.out.println(" Learning in progress。。。");
    }
}

enhancement category

package cc.wenshixin.entity;

import org.aspectj.lang.ProceedingJoinPoint;

public class StrengthStudent {
    public void beforeStudy()
    {
        System.out.println(" Pre-Enhancement。。。");
    }
    
    public void afterStudy()
    {
        System.out.println(" Rear Enhancement。。。");
    }
    
     //Wrap-around notification
    public void aroundStudy(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
    {
         //method before execution
        System.out.println(" Before the method。。。");
         // Implementation of the enhanced method
        proceedingJoinPoint.proceed();
         Executed after the // method
        System.out.println(" After the method。。。");
    }
}

configuration file

Expressions commonly used in aspectj configuration execution(< access modifier>?< Return Type>< Method name>(< parameters>)< anomaly>)

  • 1.execution(* cc.wenshixin.entity.Student.add(..))
  • 2.execution(* cc.wenshixin.entity.Student.*(..))
  • 3.execution(* *.*(..))

Note: there is a space between the first and subsequent paths, followed by two dots in parentheses, not three*

<?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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  <!-- 1. Configuration objects -->
  <bean id="student" class="cc.wenshixin.entity.Student"></bean>
  <bean id="strengthStudent" class="cc.wenshixin.entity.StrengthStudent"></bean>
  <!-- 2. configure AOP  operations -->
  <aop:config>
    <!-- 2.1  Configuration entry point -->
    <aop:pointcut expression="execution(* cc.wenshixin.entity.Student.*(..))" id="pointCut"/>
    <!-- 2.2  Configure the cut to apply enhancements to the method -->
    <aop:aspect ref="strengthStudent">
      <aop:before method="beforeStudy" pointcut-ref="pointCut"/>
      <aop:after-returning method="afterStudy" pointcut-ref="pointCut"/>
      <aop:around method="aroundStudy" pointcut-ref="pointCut"/>
    </aop:aspect>
  </aop:config>
</beans>

Test Method

package cc.wenshixin.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cc.wenshixin.entity.Student;

public class Test1 {
    @Test
    public void test()
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Student s = (Student) context.getBean("student");
        s.study();
    }
}

2.4.2 Annotation methods

Entity category as above

enhancement category AOP annotations for Aspectj

  • @Aspect:Annotations defining the cutscene enhancement class
  • Type of notification (enhancement)
    • @Before: Pre-notification
    • @AfterReturing: post-notification
    • @Around: Surround notification
    • @AfterThrowing: Exception Throwing Notification
package cc.wenshixin.entity;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class StrengthStudent {
    @Before(value="execution(* cc.wenshixin.entity.Student.*(..))")
    public void beforeStudy()
    {
        System.out.println(" Pre-Enhancement。。。");
    }
    @After(value="execution(* cc.wenshixin.entity.Student.*(..))")
    public void afterStudy()
    {
        System.out.println(" Rear Enhancement。。。");
    }
    
     //Wrap-around notification
    @Around(value="execution(* cc.wenshixin.entity.Student.*(..))")
    public void aroundStudy(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
    {
         //method before execution
        System.out.println(" Before the method。。。");
         // Implementation of the enhanced method
        proceedingJoinPoint.proceed();
         Executed after the // method
        System.out.println(" After the method。。。");
    }
}

configuration 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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  <!-- 1. Configuration objects -->
  <bean id="student" class="cc.wenshixin.entity.Student"></bean>
  <bean id="strengthStudent" class="cc.wenshixin.entity.StrengthStudent"></bean>
  <!-- 2. turn onAOP operations -->
  <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

Test method as above

3. Other concepts


3.1 Introduction to log4j

log4j is a logging package that allows you to see more detailed information about the running process of your program and view the logs. To use it, you need to import the log4j jar package. Download Location, and copy log4j of configuration file log4j.properties to the src directory.

Contents of the log4j.properties file

log4j.rootLogger Used to set the level of logging, info to see basic information, debug to see more detailed information.

#
# Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)
#
# The five logging levels used by Log are (in order):
#
#   1. DEBUG (the least serious)
#   2. INFO
#   3. WARN
#   4. ERROR
#   5. FATAL (the most serious)


# Set root logger level to WARN and append to stdout
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n

Recommended>>
1、GW Panyu Elementary and Middle School Curriculum a professional explanation of the four main features
2、Introduction to Deep Learning I
3、Python for loop and list generative difference
4、The day entertainment hall fried gold flower cheat open hang software to take good card perspective install auxiliary hang download
5、Global media trends 2018 freedom of expression and media development

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号