Skip to content

Instantly share code, notes, and snippets.

@haisi
Created September 2, 2016 08:40
Show Gist options
  • Save haisi/876aed1b5c91a84006dce2cad400880b to your computer and use it in GitHub Desktop.
Save haisi/876aed1b5c91a84006dce2cad400880b to your computer and use it in GitHub Desktop.
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
Copy link
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