How can I qualify an autowired property with a variable - spring

I am working on a Spring application and for one of my scenarios, I had to write two implementations of a Service class. I would like to know how to autowire this in a service layer based on service id at runtime.
#Autowired
ProductPricing accessProduct;
public static void main(String args[])
{
long productId = serviceDao.getService(site.getSiteID()).getServiceId();
accessProduct.calculatePrice(pricingParam)
}
public class PricingManager1 implements ProductPricing
{
public void calculatePrice(Parmeter pricingParam) {}
}
public class PricingManager2 implements ProductPricing
{
public void calculatePrice(Parmeter pricingParam) {}
}
Now depending on the productId, either the method on PricingManager1 or PricingManager2 will be called. How to achieve the same dynamically? If I autowire the Service classes with qualifier, is there any way we can pass runtime productId as qulifier in main class?

You can achieve the expected output by using #Service and then getting the bean from spring context object in your main() as shown below:
Service Classes:
#Service("pricingManager1")
public class PricingManager1 implements ProductPricing
{
public void calculatePrice(Parmeter pricingParam) {}
}
#Service("pricingManager1")
public class PricingManager2 implements ProductPricing
{
public void calculatePrice(Parmeter pricingParam) {}
}
Main Class:
//No Autowiring
public static void main(String args[])
{
long productId = serviceDao.getService(site.getSiteID()).getServiceId();
//get the spring context object
//get the bean from context
if(productId == condition) {
beanContext.getBean("pricingManager1").calculatePrice(pricingParam)
} else {
beanContext.getBean("pricingManager2").calculatePrice(pricingParam)
}
}

If you are using Spring Boot, you can achieve this by using #ConditionalOnExpression annotation and SpEL along with #Bean.
#ConditionalOnExpression("#{this.productId == 999}")
If you are not using Spring Boot, use #Conditional from Spring 4, but this will need more effort to get the same result.

Related

Java - Proper Way To Initialize an Autowired Service

I have inherited a springboot application. This application has a service similar to the following:
#Service
public class MyService {
String param1 = "";
String param2 = "";
public void doStuff() {
// do stuff assuming the parameters param1 and param 2 of this autowired service have already been initialized
}
}
, This service is autowired from another service similar to the following;
#Service
public MainService {
#Autowired MyService myService;
public performWork() {
this.myService.doStuff();
}
}
, and finally, the springboot app is similar to the following. The calling of the listen() method happens once the Kafka topic has a message (Kafka is only here relevant here because it kicks off the calling of the autowired services):
#SpringBootApplication
public class MyApplication {
#Autowired
MainService mainService;
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
#KafkaListener(topics = "myTopic")
public void listen(String message) {
this.graphicService.performWork();
}
}
Here is my question: What is a proper way to have the parameters param1 and param2 already initialized on the MyService service before its doStuff() method is called?
I would instead NOT use a bean configuration file, but rather have it performed as part of the starting of the springboot app. Any advice is appreciated. Thanks
Per my understanding, you just want to execute initialization statements at your bean's initialization. You can use PostConstruct annotation for any work you need to do as soon as beans are created.
MyService class should look like the following
#Service
public class MyService {
String param1;
String param2;
#PostConstruct
public void postConstructRoutine() {
// initialize parameters
param1 = "some_value";
param2 = "some_other_value";
}
public void doStuff() {
// do stuff
}
}
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.
You can find more info about the annotation at the documentation.
As a side note, it is always better to use constructor injection instead of Autowired. I would highly recommend it.

Spring - How to know if cglib or jdk dynamic proxy was applied to a bean

Im studying for the Spring Core cert exam, and i'm doing some testing of the framework.
I'd like to know if there is a way to know if a Bean was proxied by CGLIB or the JDK library.
I already know the basic concepts like if you declare a Bean using the interface Spring will use the JDK to proxy it (unless you tell it otherwise). And if you declare a bean directly on a class it will proxy it by inheritance using CGLIB.
What I would like to know is what should I look for while debugging to check which library was used.
Given the following code, when I debug it, I dont see any difference in the instances of the beans created. I was expecting to see something like ConcreteBean$CGLIB in the bean that has no interface...
EDIT: i now understand that proxies are only created by spring when functionality needs to be added by a PostProcessor, but still, i'd like to know what to look for in the debugger to find if CGLIB was applied or not.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = MainConfig.class)
public class ProxiesTest {
#Autowired
RandomBean randomBean;
#Autowired
ConcreteBean concreteBean;
public void setUp() {
}
#Test
public void randomBeanTest() {
randomBean.doSomething();
}
#Test
public void concreteBeanTest() {
concreteBean.doSomething();
}
}
public class ConcreteBean {
public void doSomething() {
String concreteBean = "hello";
}
#PreDestroy
public void destroy() {
System.out.print("ConcreteBean Destroy");
}
}
public interface RandomBean {
public void doSomething();
public void destroy();
}
public class RandomBeanImpl implements RandomBean {
#Autowired
ApplicationContext context;
public void doSomething() {
context.getParentBeanFactory();
}
public void destroy() {
System.out.print("RandomBean destroyed");
}
}
#Configuration
#ComponentScan(basePackages = "com.certification.postprocessors")
public class MainConfig {
#Bean
public ConcreteBean concreteBean(){
return new ConcreteBean();
}
#Bean
public RandomBean randomBean() {
return new RandomBeanImpl();
}
}
When a bean is wrapped by a Spring CGLIB proxy it states $$EnhancerBySpringCGLIB.
A JDK proxy is shown as $Proxy
It looks like this in the debugging console

how to avoid using context.getbean in spring

There have been several arguments around not using ApplicationContext.getBean() to get a bean reference, of which most are based on logic that it violates the principles of Inversion of control.
Is there a way to get reference to prototype scoped bean without calling context.getBean() ?
Consider to use Spring Boot!
Than you can do something like this...
Runner:
#SpringBootApplication
public class Runner{
public static void main(String[] args) {
SpringApplication.run(Runner.class, args);
}
}
Some Controller:
#Controller
public class MyController {
// Spring Boot injecting beans through #Autowired annotation
#Autowired
#Qualifier("CoolFeature") // Use Qualifier annotation to mark a class, if for example
// you have more than one concreate class with differant implementations of some interface.
private CoolFeature myFeature;
public void testFeature(){
myFeature.doStuff();
}
}
Some cool feature:
#Component("CoolFeature") // To identify with Qualifier
public class CoolFeature{
#Autowired
private SomeOtherBean utilityBean;
public void doStuff(){
// use utilityBean in some way
}
}
No XML files to handle.
We can still access context for manual configurations if needed.
Suggested reading:
Spring Boot Reference
Pro Spring Boot
This type of problem can be solved using method injection, which is described in more detail here: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-method-injection
This is the most common approach to create prototype bean:
abstract class MyService {
void doSome() {
OtherService otherService = getOtherService();
}
abstract OtherService getOtherService();
}
#Configuration
class Config {
#Bean
public MyService myService() {
return new MyService() {
OtherService getOtherService() {
return otherService();
}
}
}
#Bean
#Scope("prototype")
public OtherService otherService() {
return new OtherService();
}
}

Java 8 and Spring 4 : Use autowiring in interface

Java 8 added a new feature by which we can provide method implementation in interfaces.
Is there any way in Spring 4 by which we can inject beans in the interface which can be used inside the method body?
Below is the sample code
public interface TestWiring{
#Autowired
public Service service;// this is not possible as it would be static.
//Is there any way I can inject any service bean which can be used inside testWiringMethod.
default void testWiringMethod(){
// Call method of service
service.testService();
}
}
This is a bit tricky but it works if you need the dependency inside the interface for whatever requirement.
The idea would be to declare a method that will force the implemented class to provide that dependency you want to autowire.
The bad side of this approach is that if you want to provide too many dependencies the code won't be pretty since you will need one getter for each dependency.
public interface TestWiring {
public Service getService();
default void testWiringMethod(){
getService().testService();
}
}
public class TestClass implements TestWiring {
#Autowire private Service service;
#Override
public Service getService() {
return service;
}
}
You can created Class utils of application context and use it everywhere even not bean class .
you can have code somethins this :
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext context) {
ApplicationContextUtil.applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
and add this to your spring configuration
<bean class="com.example.ApplicationContextUtil" id="applicationContextUtil"/>
now simple to use when you need :
ApplicationContextUtil.getApplicationContext().getBean(SampleBean.class)
this word in web and simple spring app.

Spring can you autowire inside an abstract class?

Spring is failing to autowire my object? Is it possible to autowire an object within an abstract class. Assume all schemas are supplied in application-context.xml
Question: What annotation should be on the base and extending classes (if any) #Service #Component?
Example
abstract class SuperMan {
#Autowire
private DatabaseService databaseService;
abstract void Fly();
protected void doSuperPowerAction(Thing thing) {
//busy code
databaseService.save(thing);
}
}
Extending class
public class SuperGirl extends SuperMan {
#Override
public void Fly() {
//busy code
}
public doSomethingSuperGirlDoes() {
//busy code
doSuperPowerAction(thing)
}
application-context.xml
<context:component-scan base-package="com.baseLocation" />
<context:annotation-config/>
I have that kind of spring setup working
an abstract class with an autowired field
public abstract class AbstractJobRoute extends RouteBuilder {
#Autowired
private GlobalSettingsService settingsService;
and several children defined with #Component annotation.
Normally, Spring should do the autowiring, as long as your abstract class is in the base-package provided for component scan.
See this and this for further reference.
#Service and #Component are both stereotypes that creates beans of the annotated type inside the Spring container. As Spring Docs state,
This annotation serves as a specialization of #Component, allowing for
implementation classes to be autodetected through classpath scanning.
What if you need any database operation in SuperGirl you would inject it again into SuperGirl.
I think the main idea is using the same object reference in different classes.
So what about this:
//There is no annotation about Spring in the abstract part.
abstract class SuperMan {
private final DatabaseService databaseService;
public SuperMan(DatabaseService databaseService) {
this.databaseService = databaseService;
}
abstract void Fly();
protected void doSuperPowerAction(Thing thing) {
//busy code
databaseService.save(thing);
}
}
#Component
public class SuperGirl extends SuperMan {
private final DatabaseService databaseService;
#Autowired
public SuperGirl (DatabaseService databaseService) {
super(databaseService);
this.databaseService = databaseService;
}
#Override
public void Fly() {
//busy code
}
public doSomethingSuperGirlDoes() {
//busy code
doSuperPowerAction(thing)
}
In my opinion, inject once run everywhere :)
In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:
public abstract class EO {
#Autowired
protected SmsNotificationService smsNotificationService;
#Autowired
protected SendEmailService sendEmailService;
...
protected abstract void executeOperation(GenericMessage gMessage);
}
public final class OperationsExecutor {
public enum OperationsType {
ENROLL, CAMPAIGN
}
private OperationsExecutor() {
}
public static Object delegateOperation(OperationsType type, Object obj)
{
switch(type) {
case ENROLL:
if (obj == null) {
return new EnrollOperation();
}
return EnrollOperation.validateRequestParams(obj);
case CAMPAIGN:
if (obj == null) {
return new CampaignOperation();
}
return CampaignOperation.validateRequestParams(obj);
default:
throw new IllegalArgumentException("OperationsType not supported.");
}
}
}
#Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
#Override
public void executeOperation(GenericMessage genericMessage) {
LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
}
}
Initially to inject the dependencies in the abstract class I tried all stereotype annotations like #Component, #Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **#Configurable(dependencyCheck = true)** annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.
<context:annotation-config />
<context:component-scan base-package="com.xyz" />
I also tried these other references to find a solution:
http://www.captaindebug.com/2011/06/implementing-springs-factorybean.html#.WqF5pJPwaAN
http://forum.spring.io/forum/spring-projects/container/46815-problem-with-autowired-in-abstract-class
https://github.com/cavallefano/Abstract-Factory-Pattern-Spring-Annotation
http://www.jcombat.com/spring/factory-implementation-using-servicelocatorfactorybean-in-spring
https://www.madbit.org/blog/programming/1074/1074/#sthash.XEJXdIR5.dpbs
Using abstract factory with Spring framework
Spring Autowiring not working for Abstract classes
Inject spring dependency in abstract super class
Spring and Abstract class - injecting properties in abstract classes
Spring autowire dependency defined in an abstract class
Please try using **#Configurable(dependencyCheck = true)** and update this post, I might try helping you if you face any problems.

Resources