Friends below is my code, I am trying to run dependency Injection with Spring
I have an interface, two class implementations of that interface.
One bean.xml and One main method class.
Interface IWriter.java
package DI;
public interface IWriter {
public void writer(String s);
}
Class Writer.java
package DI;
import org.springframework.stereotype.Service;
#Service
public class Writer implements IWriter {
public void writer (String s){
System.out.println(s);
}
}
Class NiceWriter.java
package DI;
import org.springframework.stereotype.Service;
#Service
public class NiceWriter implements IWriter {
public void writer (String s){
System.out.println("The string is " + s);
}
}
Another class
package DI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
#Service
public class MySpringBeanWithDependency {
#Autowired
private IWriter writer;
public void run() {
String s = "This is my test";
writer.writer(s);
}
}
Main.java
package DI;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import DI.MySpringBeanWithDependency;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
BeanFactory factory = context;
MySpringBeanWithDependency test = (MySpringBeanWithDependency) factory.getBean("mySpringBeanWithDependency");
test.run();
}
}
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="DI" />
</beans>
When I run the code Spring container gives the output of the method of Writer.java class. I haven't anywhere specified which implementation to pick. How is Spring picking up the implementation of Writer.java??
change your code as follows.
Class Writer.java
package DI;
import org.springframework.stereotype.Service;
#Service("writer")
public class Writer implements IWriter {
public void writer (String s){
System.out.println(s);
}
}
Class NiceWriter.java
package DI;
import org.springframework.stereotype.Service;
#Service("niceWriter")
public class NiceWriter implements IWriter {
public void writer (String s){
System.out.println("The string is " + s);
}
}
Another class
package DI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
#Service
public class MySpringBeanWithDependency {
#Autowired
#Qualifier("writer")//if you need to autowire Writer service
private IWriter writer;
#Autowired
#Qualifier("niceWriter")//if you need to autowire NiceWriter service
private IWriter niceWriter
public void run() {
String s = "This is my test";
writer.writer(s);
}
}
When there is more than one implementation of interface and you use #Autowired in that case spring bind any of the class. but if you want to autowire specific implementation then you can use
#Qualifier( "<implementing class name>" )
#Qualifier documentation
Few things that you must know about Spring is
All spring beans are managed - they "live" inside a container, called "application context".
Each application has an entry point to that context. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.
Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.
Try this one.
Class Writer.java
package DI;
import org.springframework.stereotype.Service;
#Service("writer")
public class Writer implements IWriter {
public void writer (String s){
System.out.println(s);
}
}
Class NiceWriter.java
package DI;
import org.springframework.stereotype.Service;
#Service("niceWriter")
public class NiceWriter implements IWriter {
public void writer (String s){
System.out.println("The string is " + s);
}
}
Another class
package DI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
#Service
public class MySpringBeanWithDependency {
#Autowired
private IWriter writer;
#Autowired
private IWriter niceWriter
public void run() {
String s = "This is my test";
writer.writer(s);
}
}
I'd like to show one more option using application.properties.
Benefits:
You don't need to change code when you add/change implementation of the interface
Works well with unit tests and other environments
Sample code based on #ConditionalOnProperty attribute
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
#Service
#ConditionalOnProperty(value = "writer.type", havingValue = "default")
public class Writer implements IWriter {
#Override
public void writer(String s) {
System.out.println("The string is " + s);
}
}
And
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
#Service
#ConditionalOnProperty(value = "writer.type", havingValue = "nice")
public class NiceWriter implements IWriter {
#Override
public void writer(String s) {
System.out.println("Nice string is " + s);
}
}
When application.properties contains writer.type=nice NiceWriter will be instantiated for IWriter interface.
Instead of #ConditionalOnProperty there are other options like Conditional, #ConditionalOnExpression.
It depends on the use-case, you can select implementation of the interface using spring profiles, custom annotations or as mentioned by other answers using #Qualifier (injection by name) which is equivalent to JSR-330's #Named annotation
Related
I have these classes. when I debug I see that the spring creates the service object in constructor and called the constructors in both classes but when I want to use the fields, they are null. What's the problem?! (type1Processor, type2Processor and type3Processor are null)
import com.vali.ReactiveSocketServer.service.ReceivedDataService;
import org.springframework.stereotype.Component;
public abstract class Processor {
public ReceivedDataService receivedDataService;
public Processor(ReceivedDataService receivedDataService) {
this.receivedDataService = receivedDataService;
}
public abstract void readStream(String stream);
}
and this is its subclass
import com.vali.ReactiveSocketServer.model.ReceivedData;
import com.vali.ReactiveSocketServer.service.ReceivedDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class Type1Processor extends Processor {
#Autowired
public Type1Processor(ReceivedDataService receivedDataService) {
super(receivedDataService);
}
#Override
public void readStream(String stream) {
System.out.println("readStream "+ getClass().getSimpleName() + "-" + stream);
receivedDataService.add(new ReceivedData(stream.getBytes()));
}
}
and this is its usage:
import com.vali.ReactiveSocketServer.processor.Processor;
import com.vali.ReactiveSocketServer.processor.Type1Processor;
import com.vali.ReactiveSocketServer.processor.Type2Processor;
import com.vali.ReactiveSocketServer.processor.Type3Processor;
import com.vali.ReactiveSocketServer.receivers.AppServer;
import com.vali.ReactiveSocketServer.socket.ClientHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.HashMap;
import java.util.Map;
#SpringBootApplication
public class ReactiveSocketServerApplication {
private AppServer appServer;
#Autowired
Type1Processor type1Processor;
#Autowired
Type2Processor type2Processor;
#Autowired
Type3Processor type3Processor;
public static void main(String[] args) {
SpringApplication.run(ReactiveSocketServerApplication.class, args);
ReactiveSocketServerApplication reactiveSocketServerApplication = new ReactiveSocketServerApplication();
reactiveSocketServerApplication.Start();
}
public void Start(){
appServer = AppServer.getInstance();
Map<Integer, Processor> processorMap = new HashMap<>();
processorMap.put(7001, type1Processor);
processorMap.put(7002, type2Processor);
processorMap.put(7003, type3Processor);
appServer.initialize(processorMap);
new ClientHandler(7001, 1000);
new ClientHandler(7002, 5000);
}
}
You are instantiating ReactiveSocketServerApplication yourself.
So spring can't inject the #Autowired annotated beans, because the instance was created outside of it's life cycle.
Remove this completly:
ReactiveSocketServerApplication reactiveSocketServerApplication = new ReactiveSocketServerApplication();
reactiveSocketServerApplication.Start();
And annotate your Start() with #PostConstruct:
#PostConstruct
public void Start() { ... }
You are missing #Component in the abstract class ReceivedDataService.
This mean when you create the subclases using :
#Autowired
public Type1Processor(ReceivedDataService receivedDataService) {
super(receivedDataService);
}
Can't inject ReceivedDataService and get the default value(null)
I'm learning Springs with annotations and auto wiring. I tried three types of auto wiring
Constructor
Setter injection
Method
This is my configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- add entry for component scanning -->
<context:component-scan base-package="com.aht.spring.entity"></context:component-scan>
</beans>
These are my entities
Coach.java
package com.aht.spring.entity.coach;
public interface Coach {
String getDailyWorkOut();
String getDailyFortune();
}
FortuneService
package com.aht.spring.entity.fortune;
public interface FortuneService {
String getFortune();
}
HappyFortuneService
package com.aht.spring.entity.fortune;
import org.springframework.stereotype.Component;
#Component
public class HappyFortuneService implements FortuneService {
public String getFortune() {
return "Feel energetic for first half of trainning";
}
}
FootBallCoach
package com.aht.spring.entity.coach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.aht.spring.entity.fortune.FortuneService;
#Component
public class FootBallCoach implements Coach {
private FortuneService fortuneService;
#Autowired
public FootBallCoach(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}
public String getDailyWorkOut() {
return "Practice one-on-one for 2 hours";
}
public String getDailyFortune() {
return fortuneService.getFortune();
}
}
CricketCoach
package com.aht.spring.entity.coach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.aht.spring.entity.fortune.FortuneService;
#Component
public class CricketCoach implements Coach {
private FortuneService fortuneService;
public CricketCoach() {
System.out.println("Default constructor");
}
#Autowired
public void setFortuneService(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}
public String getDailyWorkOut() {
return "Practice out field tips";
}
public String getDailyFortune() {
return fortuneService.getFortune();
}
}
BaseBallCoach
package com.aht.spring.entity.coach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.aht.spring.entity.fortune.FortuneService;
#Component
public class BaseBallCoach implements Coach {
private FortuneService fortuneService;
public String getDailyWorkOut() {
return "Practice curve whole day";
}
public String getDailyFortune() {
return fortuneService.getFortune();
}
#Autowired
public void customAutoWire(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}
}
I've three classes for executing three ways of auto wiring, Constructor and Setter worked fine, but when method wise auto wiring was done a wrong constructor was called. One thing I missed in my in my BaseBallCoach class was a default constructor, but anyhow compiler will automatically generate one for me right?
This is my CoachMethodInjectionApp.java where I executed method auto wiring
package com.aht.spring.app;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.aht.spring.entity.coach.Coach;
public class CoachMethodInjectionApp {
public static void main(String[] args) {
// read config-file
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// get beans
Coach coach = context.getBean("baseBallCoach", Coach.class);
// get dependencies
System.out.println(coach.getDailyFortune());
// get daily workout
System.out.println(coach.getDailyWorkOut());
// close context
context.close();
}
}
This was the output
Default constructor
Feel energetic for first half of trainning
Practice curve whole day
First line of output is what I don't understand Default constructor, why the constructor of CricketCoach executing??
As CricketCoach class is annotated with #Component and the package is scanned when the Spring container starts it will create an instance of type CricketCoach by calling the no-arg constructor
All the beans defined in the xml file or annotated with #Component or any extension of #Component from scanned packages will be created at start time of the spring container no matter if they will be used or not
You're creating a new instance of Coach class here:
Coach coach = context.getBean("baseBallCoach", Coach.class);
Everytime new instance is created it is executing a constructor. In which you have call to System.out.println("Default constructor");. You may try removing #Component from Cricket Coach imlpementation.
I am new to Spring AOP and annotations. I tried to write a simple program that uses Aspect. I am unable to figure out where I went wrong. Its doesn't print the what I have in my Aspect.
package com.business.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
#EnableAspectJAutoProxy
#Configuration
public class PrintMain {
public static void main(String[] args) {
// Do I always need to have this. Can't I just use #Autowired to get beans
ApplicationContext ctx = new AnnotationConfigApplicationContext(PrintMain.class);
CheckService ck = (CheckService)ctx.getBean("service");
ck.print();
}
#Bean(name="service")
public CheckService service(){
return new CheckService();
}
}
package com.business.main;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class SimpleAspect {
#Around("execution(* com.business.main.CheckService.*(..))")
public void applyAdvice(){
System.out.println("Aspect executed");
}
}
package com.business.main;
import org.springframework.stereotype.Component;
#Component
public class CheckService{
public void print(){
System.out.println("Executed service method");
}
}
Output: Executed service method
I expect to print what I have in my Aspect
I think your #Component isn't work!
Maybe, you need the #ComponentScan
#EnableAspectJAutoProxy
#ComponentScan
#Configuration
public class PrintMain {
public static void main(String[] args) {
// Do I always need to have this. Can't I just use #Autowired to get beans
ApplicationContext ctx = new AnnotationConfigApplicationContext(TNGPrintMain.class);
CheckService ck = (CheckService)ctx.getBean("service");
ck.print();
}
#Bean(name="service")
public CheckService service(){
return new CheckService();
}
}
AppConfig contains Java Configuration.
package com.wh;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;
#Configuration
#EnableSpringConfigured
#EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
public class AppConfig {
#Bean
#Lazy
public EchoService echoService(){
return new EchoService();
}
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
}
Service Class
package com.wh;
import org.springframework.stereotype.Service;
#Service
public class EchoService {
public void echo( String s ) {
System.out.println( s );
}
}
EchoDelegateService is the Non Bean class in which we have Autowired The required Bean.
We expect that the EchoService should get autowired.
Problem : EchoService not getting autowired. Gives an Null Pointer exception.
package com.wh;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
#Configurable( preConstruction = true, autowire = Autowire.BY_TYPE, dependencyCheck = false )
public class EchoDelegateService {
#Autowired
private EchoService echoService;
public void echo( String s ) {
echoService.echo( s );
}
}
Main Class where we are calling method of NonBean Class.
package com.wh;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class);
new EchoDelegateService().echo("hihi, it works...");
}
}
Your question already includes the answer: "... in a non-bean class". This simply does not work. All the autowiring, aspect resolving and whatever is to that, only works for beans. Thus, you definitely need to construct your EchoDelegateService via the spring factory:
EchoDelegateService myService = ctx.getBean(EchoDelegateService.class);
myService.echo("this should really work now");
I try to improve my Spring knowledge by reading Spring in action 4.
When I've to to section, describing using of Qualifier annotation (3.3.2), i faced the problem.
To test this annotation in action, I wrote Dessert interface, which is implemented by 3 classes, creating in context using #Component annotation.
I also created class Taster, which "tastes" some dessert, autowired into by some qualifier.
When I run my application, using AnnotationConfigApplicationContext - everything works good. With SpringJUnit4ClassRunner - it does not. I guess I miss something in my test code, but I do not have enough knowledge to realize what.
Interface:
package bakery.intrface;
#FunctionalInterface
public interface Dessert {
void introduce();
}
Cake:
package bakery.desserts;
import bakery.intrface.Dessert;
import org.springframework.stereotype.Component;
#Component
public class Cake implements Dessert {
#Override
public void introduce() {
System.out.println("I am a cake!");
}
}
Cookie:
package bakery.desserts;
import bakery.intrface.Dessert;
import org.springframework.stereotype.Component;
#Component
public class Cookie implements Dessert {
#Override
public void introduce() {
System.out.println("I'm a cookie!");
}
}
Ice cream:
package bakery.desserts;
import bakery.intrface.Dessert;
import org.springframework.stereotype.Component;
#Component
public class IceCream implements Dessert {
#Override
public void introduce() {
System.out.println("I'm an ice cream!");
}
}
The class, consumes some bean, Taster:
package bakery;
import bakery.intrface.Dessert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
public class Taster {
private Dessert dessert;
public void taste(){
dessert.introduce();
}
#Autowired
#Qualifier("iceCream")
public void setDessert(Dessert dessert) {
this.dessert = dessert;
}
}
Configuration:
package bakery.config;
import bakery.Bakery;
import bakery.Taster;
import bakery.desserts.Cake;
import bakery.intrface.Dessert;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan(basePackageClasses = Bakery.class)
public class BakeryConfig {
}
Run class:
package bakery;
import bakery.config.BakeryConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Bakery {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BakeryConfig.class);
String[] beans = context.getBeanDefinitionNames();
Taster taster = (Taster) context.getBean("taster");
taster.taste();
}
}
Test class:
package bakery;
import bakery.config.BakeryConfig;
import bakery.intrface.Dessert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertNotNull;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = BakeryConfig.class)
public class BakeryTest {
#Autowired
Dessert dessert;
#Autowired
Taster taster;
#Test
public void contextInit(){
assertNotNull(dessert);
dessert.introduce();
}
#Test
public void tasterInit(){
assertNotNull(taster);
}
}
When I run the test, I'm getting the exception: No qualifying bean of type [bakery.intrface.Dessert] is defined: expected single matching bean but found 3: cookie,iceCream,cake.
There are 3 "Dessert" beans in your application context, you have to specify which one you want to wire.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = BakeryConfig.class)
public class BakeryTest {
#Autowired
#Qualifier("iceCream") // <===================== you must specify which bean to be wired
Dessert dessert;
#Autowired
Taster taster;
This is to be expected.
The declaration
#Autowired
Dessert dessert;
is asking for a Dessert object. Dessert is the interface, and there are three implementing classes, Cookie, IceCream, and Cake. Since you haven't made it more explicit which of those implementations you want, Spring throws an error because it can't decide what to do.
If you need this in your test, you can do one of the following:
#Autowired
#Qualifier("iceCream")
Dessert dessert;
to get only the ice cream dessert,
OR
#Autowired
List<Dessert> desserts;
to get a list containing all the implementations.