package com.jay.prj.mybaits;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Role;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.sql.SQLException;

@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Application {

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
        DataSource bean = (DataSource) run.getBean("dataSource2");
        try {
            System.out.println(bean.getConnection());
        } catch(SQLException e) { e.printStackTrace(); }}@Bean(name = "dataSource2")
    @Role(BeanDefinition.ROLE_SUPPORT)
    public DataSource dataSource(a) {
        return new PooledDataSource();
    }

    
    /** * agent conditions */
    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public DefaultBeanFactoryPointcutAdvisor transactionAdvisor(a) {
        DefaultBeanFactoryPointcutAdvisor advisor = new DefaultBeanFactoryPointcutAdvisor();
        advisor.setPointcut(staticMethodMatcherPointcut());
        advisor.setAdvice(transactionInterceptor());
        return advisor;
    }

    /** * Proxy condition judgment *@return* /
    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public StaticMethodMatcherPointcut staticMethodMatcherPointcut(a) {
        return new StaticMethodMatcherPointcut() {
            public boolean matches(Method method, Class
        aClass) {
                return DataSource.class.isAssignableFrom(aClass) && method.getName().equals("getConnection"); }}; }/** * function proxy logic */
    public MethodInterceptor transactionInterceptor(a) {
        return new MethodInterceptor() {
            public Object invoke(MethodInvocation methodInvocation) throws Throwable {
                System.out.println("Method run before");
                return null; }}; }}Copy the code

Execution Result:

The 2021-06-11 11:11:14. 10776-820 the INFO [main] S.B.C.E.T.T omcatEmbeddedServletContainer: Tomcat started on the port (s) : 2998 (HTTP) 11:11:14 2021-06-11. 10776-826 the INFO [main] com. Jay. PRJ. Mybaits. Application: Started Application in 4.8 seconds (JVM running for 5.775 org. Apache. Ibatis. The datasource. The pooled. PooledDataSource @ 1690 e14 Null before the method runsCopy the code