Spring Core Foundation Explanation

Spring Basic Explanation

Spring Basic Concepts

This article only focuses on IoC and AOP.

IoC (Control Inversion)

Inversion of Control (IoC), also known as Dependency Injection, is a design concept in object-oriented programming to reduce the coupling between program codes.

First import the corresponding jar

  1. commons-logging-.jar
  2. log4j.jar
  3. spring-beans.jar
  4. spring-context.jar
  5. spring-core.jar
  6. spring-expression.jar

Here I did not specify the specified version, according to their own needs to download the corresponding version.
Here we use log4j to control the log output to view the log.

Then write the Spring configuration file and add the application.xml file to the project classpath root path.
Note the creation of a source folder package in eclipse

<bean id="zhangGa" class="pojo.Greeting">
    <property name="person">
        <value>Zhang Jia</value>
    </property>
    <property name="words">
        <value>If you don't hit a kid for three days, your hands itch.</value>
    </property>
</bean>

The configuration file is basically the same as above.

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Player player=(Player)context.getBean("zhangSan");
System.out.println(player.getRing().getName()+"[Speed efficiency:"+player.getRing().getSpeedPlus()
+";Attack synergy:"+player.getRing().getAttackPlus()+";Self-defense synergies:"+player.getRing().getDefencePlus()+"]");

Then test as above in test

Knowledge Extension: Application Context and Implementation Class. Bean Components can also be managed through BeanFactory Interface and Implementation Class. In fact, Application Context is based on BeanFactory.

BeanFactory is the core of Spring IoC container. It manages components and their dependencies. Applications interact with each other through BenaFactory interface and Spring IoC container.

Here we can use the corresponding annotations to achieve the corresponding function, which is also our common way.

@Component("userDao")
public class UserDaoImpl implements UserDao {

    @Override
    public void save(User user) {
        System.out.println("Save user information to database");
    }

}

The above code defines a Bean named userDao
Spring also provides three special annotations

@ Repository: Used to annotate DAO classes
@ Service: Used to annotate business classes
@ Controller: Used to annotate controller classes

Spring provides @Autowire annotations for bean assembly
Implementing Automatic Assembly Objects
@ Autowire automatically assembles appropriate dependent objects for attributes by type matching
If there is more than one bean in the container that matches each other, you can specify the required bean name using @Qualifier

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public UserMapper getUserMapper() {
        return userMapper;
    }

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<User> findUsersWithConditions(User user) {
        try {
            return userMapper.getUserList(user);
        }catch (RuntimeException r){
            r.printStackTrace();
            throw r;
        }
    }
   }

Add in the application.xml file

Classes Annotated in Scan Pack
<context:component-scan base-package="dao"/>
<bean class="dao.UserServiceLogger"/>
<aop:aspectj-autoproxy/>

It can be used immediately.

AOP (Aspect-Oriented Programming)

Aspect-oriented programming is the product of the development of software programming thought to a certain stage, and it is a useful supplement to object-oriented programming.
Aspect-oriented programming simply means adding new functions to code segments without changing the original program. Enhance the code segment.

1. Aspects: A modular crosscutting logic that may cross-cut multiple objects
2. Connection Point: A specific execution point in program execution
3. Additional Processing: Logic that the facet executes at a particular join point
4. Cut-in point: Describe the characteristics of join points, using regular expressions
5. Target objects: objects enhanced by one or more facets
6.AOP proxy: Objects created by AOP framework to implement functions such as enhanced processing.
7. Weaving: The process of connecting enhanced processing to types or objects in an application
8. Enhancement processing type: After normal execution, the insertion of enhancements is post-enhancements, where there are surround enhancements, exception throw enhancements, and ultimately enhancements.

Use importing the corresponding jar package
1.aopalliance.jar
2.aspectjweaver.jar
3.spring-aop.jar

private static final Logger log=Logger.getLogger(UserServiceLogger.class);

//Representational Pre-Enhancement Method
public void befpre(JoinPoint jp){
    log.info("call"+jp.getTarget()+"Of"+jp.getSignature().getName()+"Method. Method Involvement"+ Arrays.toString(jp.getArgs()));
}

//Representational Postposition Method
public void afterReturning(JoinPoint jp,Object result){
    log.info("call"+jp.getTarget()+"Of"+jp.getSignature().getName()+"Method. Method return value:"+result);
}

Add aop file configuration in application.xml
Add Pack

<aop:config>
    <aop:pointcut expression="execution(public void addNewUser(pojo.User))" id="pointcut"/>
    <aop:aspect ref="theLogger">
        <aop:before method="befpre" pointcut-ref="pointcut"></aop:before>
       <!-- adopt returning Property specifies a name result Parameter injection return value-->
        <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
    </aop:aspect>
</aop:config>

As above cut in
execution is a pointcut indicator, and its parentheses are a pointcut expression.
Fuzzy Matching

Public * addNewUser(entity.User); * Represents a return value that matches all types
Pulbic void *(entity.User) * denotes matching all method names
Public void addNewUser(... );... Represents the number and type of all parameters matched
* com.service. *. * (... Represents all methods that match all classes under com.service. package
* com.service... * *(...) Represents all methods that match all classes under the com. service package and its subpackages

Abnormal throw enhancement
Anomaly throw enhancement is characterized by weaving reinforcement processing when the target method throws an exception.

<aop:pointcut id="pointcut" expression="execution(* dao.UserService.*(..))"/>
<aop:aspect ref="theLogger">
    <aop:after-throwing method="afterReturning" pointcut-ref="pointcut" throwing="e"/>
</aop:aspect>


public class ErrorLogger {
    private static final Logger log=Logger.getLogger(ErrorLogger.class);


    public void afterThrowing(JoinPoint jp,RuntimeException e){
        log.error(jp.getSignature().getName()+"Method Abnormality"+e);
    }
}

6.2.2 Enhancement
The feature of the final enhancement is that regardless of whether the method throws an exception or does not exit normally, the enhancement will be implemented.

application.xml file

   <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* dao.UserService.*(..))"/>
        <aop:aspect ref="theLogger">
            <aop:after method="afterLogger" pointcut-ref="pointcut" />
        </aop:aspect>
    </aop:config>-

Entity class

   public class AfterLogger {
        private static final Logger log=Logger.getLogger(AfterLogger.class);
    
        public void afterLogger(JoinPoint jp){
            log.info(jp.getSignature().getName()+"Method ends execution.");
        }
    }

6.2.3 Enhanced Circumference
Enhancement can be woven into the surround enhancement before and after the target method. Enhancement of surround is the most powerful enhancement processing.
public class AroundLogger {
private static final Logger log=Logger.getLogger(AroundLogger.class);

public Object arcoundLogger(ProceedingJoinPoint jp) throws Throwable{
    log.info("call"+jp.getTarget()+"Of"+jp.getSignature().getName()+"Method. Method Involvement"+ Arrays.toString(jp.getArgs()));
    Object result=jp.proceed();
    try {
        log.info("call"+jp.getTarget()+"Of"+jp.getSignature().getName()+"Method, method return value "+result);
        return result;
    } catch (Exception e) {
        log.error(jp.getSignature().getName()+"Method Abnormality"+e);
        throw e;
    } finally {
        log.info(jp.getSignature().getName()+"Method End Execution");
    }
}

Configuration file

  <aop:pointcut id="pointcut" expression="execution(* dao.UserService.*(..))"/>
    <aop:aspect ref="theLogger">
        <aop:around  method="arcoundLogger" pointcut-ref="pointcut" />
    </aop:aspect>

Generally speaking, it is much more convenient for us to use annotations.

For example:

Introduction to AspectJ
AspectsJ is an aspect-oriented framework that extends the Java language, defines AOP syntax and provides code weaving at compile time, so it has a special compiler to generate Class files that comply with byte coding specifications.
Spring realizes annotation aspect by integrating AspectJ, which greatly reduces the workload of configuration files.

6.4.2 Use annotations to mark sections

@Aspect
public class AfterLogger {
    private static final Logger log=Logger.getLogger(AfterLogger.class);
@After("execution(* dao.UserService.*(..))")
public void afterLogger(JoinPoint jp){
    log.info(jp.getSignature().getName()+"Method ends execution.");
}

}

In this way, you can configure it without using the application.xml file

Keywords: Spring Programming xml log4j

Added by menelaus8888 on Mon, 12 Aug 2019 15:34:08 +0300