The bean injected in mybatis custom interceptor plug-in is empty

Time:2020-9-19

background

In the internship work, the Department is improving the security tools middleware to strengthen the project, includingData desensitization based on mybatis interceptorTools for

The working principle is as follows:The bean injected in mybatis custom interceptor plug-in is empty

problem

When encrypting sensitive data during the call, null pointer exception was found, which was found to be injected by debugEncryptManagerIs empty
Interceptor code

@Intercepts({
       @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
       @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
       @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
@Component
@Slf4j
public class DbInterceptor implements Interceptor {
   @Autowired
   Private encryptmanager encryptmanager; // encryption implementation class

reason

Mybatis’s plug-in is fully initialized before the spring container. Although adding @ component will be scanned and added to the container management, the object encryptmanager injected by the mybatis interceptor dbinterceptor has not been initialized to the container.
So the bean obtained in this way is empty.

solve

Get the bean from the spring container when executing the interception method
(there is no need to write an initialization class to implement the afterpropertieset() method of the initializingbean interface to set the bean to the mybatis interceptor later.)

@Override
    public Object intercept(Invocation invocation) throws Throwable {
            If ( ApolloConfigManager.isCrypticSwitch () // configure whether to enable interceptor through Apollo 
            {
                if(encryptManager==null) {
           encryptManager=ApplicationUtils.getApplicationContext().getBean(EncryptManager.class);
                }
                
                return aesIntercept(invocation);
            }else{
                return invocation.proceed();
            }
    }

Recommended Today

Solutions to leetcode problems and knowledge points 1. Sum of two numbers

Title Link 1. Two Sum  difficulty: $/ color {00965e} {easy}$ Knowledge points 1. Hash (hash) function The classic hash function times33 is widely used, and the core algorithm is as follows: hash(i) = hash(i-1) * 33 + str[i] Laruence has an article about:Hash algorithm in PHP 2. Hash collision processing method 2.1 chain address method […]