Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.annotation.SessionScope;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.logging.Logger;
@Configuration
public class LoggingProvider {
@Bean
@Scope("prototype")
@SessionScope
public java.util.logging.Logger createLogger(InjectionPoint ip) {
final String simpleName = ip.getMember().getDeclaringClass().getName();
return Logger.getLogger(simpleName);
}
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
CommandLineRunner runner(java.util.logging.Logger logger) {
return args -> {
System.out.println(logger.getName());
logger.log(Level.INFO, "Test level info");
};
}
}
@haisi

This comment has been minimized.

Copy link
Owner Author

haisi commented Sep 2, 2016

With Spring 4.3 you can easily get the injection point to create cool context dependent injections.
In this example I inject a correctly configured logger. So instead of writing something like

private final static Logger LOGGER = Logger.getLogger(MyLogger.class.getName()); 

I can simple inject it like:

@Inject
Logger logger;

Note that with InjectionPoint you have access to even more meta-data like the annotations used on the injection-field, for example if you create your custom annotation you can make really customizable injections of beans.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.