Access spring bean from appender registration class

I have a log4j class DailyRollingFileAppender in which the setFile () method I need to check the database value to decide which file to use for logging.

DailyRollingFileAppender class 

public void setFileName()
{
    isLoginEnabled = authenticationManager.checkLoginLogging();
}

Here, "authenticationManager" is a class object used to invoke a database using the spring dependency insert function.

spring-beans.xml
<bean id="dailyRollingFileAppender" class="com.common.util.DailyRollingFileAppender">
 <property name="authenticationManager">
     <ref bean="authenticationManager"/>
 </property>
</bean>

<bean id="authenticationManager" class="com.security.impl.AuthenticationManagerImpl">
    <property name="userService">
        <ref bean="userService"/>
</property>
</bean>

Now, when I launch my application, log4j starts first, and since spring beans has not yet been called, it throws a NullPointerException in the setFileName () method. So I can make a call to "authenticationManager.checkLoginLogging ();" from the DailyFileAppender class so that when log4j is loaded it can get the database value?

+3
1

, , - .

- appender, autwired bean , . , ApplicationContextAware, , , , , spring - bean , log4j.

@Component
public class SslErrorSecurityAppender extends AppenderSkeleton implements ApplicationContextAware {

    private static SecurityLogger securityLogger;

    @Override
    protected void append(LoggingEvent event) {
        securityLogger.log(new SslExceptionSecurityEvent(SecurityEventType.AUTHENTICATION_FAILED, event.getThrowableInformation().getThrowable(), "Unexpected SSL error"));
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    @Override
    public synchronized void close() {
        this.closed = true;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (applicationContext.getAutowireCapableBeanFactory().getBean("securityLogger") != null) {
            securityLogger = (SecurityLogger) applicationContext.getAutowireCapableBeanFactory().getBean("securityLogger");
        }
    }
}
+8

Source: https://habr.com/ru/post/1722805/


All Articles