Spring Download - How is an @Autowired Bean with a non-standard constructor?

I found a lot of information about using @Autowired with a non-empty constructor here . But I can’t even solve my current problem.

I have an interface for logging. I register every record in the database. For this reason, it is important for me to know the name of the class in which the class uses the registrar.

My first idea: Create a new Logger implementation that has a non-empty constructor. So, when creating a new instance of this registrar, you must set the name.

My interface is as follows:

public interface Logger{
  public void log(String name, String msg);
}

The implementation of this looks like this:

@Service
public class LoggerImpl implements Logger{
 private String className;

 LoggerImpl(String className){ this.className = className }

 @Override
 public void log(String name, String msg) { // print and save in the database }
}

And everywhere in my application I want to use this logger - Interface. For example, in some business classes, I use Logger this way:

@Service
public class ServiceName {
 private Logger logger;

 @Autowired
 public ServiceName(){
   logger = new LoggerImpl("ServiceName");
 }

 public void someMethod(){
    logger.log("name", "this is a log!");
 }
}

, NullPointerException, . . , LoggerImpl spring. ? . . spring Boot XML .

+4
2

, @Service . Spring LoggerImpl.

Spring, . XML

<bean id="loggerForX" class="LoggerImpl ">
  <constructor-arg index="0" value="X" />
</bean>

javaconfig

@Configuration
public class LoggerConfiguration {

  @Bean
  public Logger loggerForX() {
    return new LoggerImpl("X");
  }

}

@Autowire Logger

@Autowire  Logger loggerForX;

, autowiring loggerForX variable ab

@Autowire @Qualifier("loggerForX") Logger loggerForX;

bean , . LoggerFactory bean LoggerFactory. LoggerFactory Logger.

@Service
class LoggerFactory  {

  public Logger loggerFor(String name) {
    return new LoggerImpl(name);
    }

}

LoggerFactory @Autowired , .

+4

, InjectionPoint

@Configuration
public class LoggerConfig {

  @Bean
  @Scope("prototype")
  public Logger logger(InjectionPoint injectionPoint) {
    //this is the class where the logger will be used     
    Class<?> theClassYouAreLookingFor = injectionPoint.getMember().getDeclaringClass();
    return findOrCreateYourLogger(theClassYouAreLookingFor);
  }
}

Logger, , , Bean.

+4

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


All Articles