Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.baeldung.dependencyinjectiontypes;

import org.springframework.beans.factory.annotation.Autowired;


public class ConstructorInjection {

private final MyInjectedBean myInjectedBean;

@Autowired
public ConstructorInjection(MyInjectedBean myInjectedBean) {
this.myInjectedBean = myInjectedBean;
}

public MyInjectedBean getMyInjectedBean() {
return myInjectedBean;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.baeldung.dependencyinjectiontypes;

import org.springframework.stereotype.Component;


@Component
public class MyInjectedBean
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.baeldung.dependencyinjectiontypes;

import org.springframework.beans.factory.annotation.Autowired;


public class SetterInjection
{

private MyInjectedBean myInjectedBean;

@Autowired
public void setMyInjectedBean(MyInjectedBean myInjectedBean) {
this.myInjectedBean = myInjectedBean;
}

public MyInjectedBean getMyInjectedBean() {
return myInjectedBean;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.baeldung.dependencyinjectiontypes;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


public class InjectionTest
{

private AnnotationConfigApplicationContext ctx;

@Before
public void setUp() {
ctx = new AnnotationConfigApplicationContext(MyInjectedBean.class, ConstructorInjection.class, SetterInjection.class);
}

@Test
public void testConstructorInjection() {
ConstructorInjection constructorInjection = ctx.getBean(ConstructorInjection.class);
Assert.assertNotNull(constructorInjection.getMyInjectedBean());
}

@Test
public void testSetterInjection() {
SetterInjection setterInjection = ctx.getBean(SetterInjection.class);
Assert.assertNotNull(setterInjection.getMyInjectedBean());
}

@Test
public void testSetterInjectionNonMandatory() {
SetterInjection setterInjection = new SetterInjection();
Assert.assertNull(setterInjection.getMyInjectedBean());
}
}