File tree Expand file tree Collapse file tree
main/java/com/baeldung/ditypes
test/java/com/baeldung/ditypes Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .ditypes ;
2+
3+ import org .springframework .context .annotation .Bean ;
4+ import org .springframework .context .annotation .ComponentScan ;
5+ import org .springframework .context .annotation .Configuration ;
6+
7+ @ Configuration
8+ @ ComponentScan ("com.baeldung.ditypes" )
9+ public class RegisterarConfig {
10+ @ Bean
11+ public User user () {
12+ return new User ("Alice" , 1 );
13+ }
14+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .ditypes ;
2+
3+ import org .springframework .beans .factory .annotation .Autowired ;
4+ import org .springframework .stereotype .Component ;
5+
6+ @ Component
7+ public class Registrar {
8+ private User user ;
9+
10+ @ Autowired
11+ public Registrar (User user ) {
12+ this .user = user ;
13+ }
14+
15+ public String register () {
16+ return user .register ();
17+ }
18+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .ditypes ;
2+
3+ import org .springframework .stereotype .Component ;
4+
5+ @ Component
6+ public class User {
7+
8+ private String name ;
9+ private int id ;
10+
11+ public User (String name , int id ) {
12+ this .id = id ;
13+ this .name = name ;
14+ }
15+
16+ public String register () {
17+ return "User" + id + ": " + name + " is registered" ;
18+ }
19+
20+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .ditypes ;
2+
3+ import static org .junit .Assert .*;
4+ import org .junit .Test ;
5+ import org .junit .runner .RunWith ;
6+ import org .springframework .beans .factory .annotation .Autowired ;
7+ import org .springframework .test .context .ContextConfiguration ;
8+ import org .springframework .test .context .junit4 .SpringJUnit4ClassRunner ;
9+
10+ @ RunWith (SpringJUnit4ClassRunner .class )
11+ @ ContextConfiguration (classes = RegisterarConfig .class )
12+ public class RegisterarTest {
13+
14+ @ Autowired
15+ private Registrar reg ;
16+
17+ @ Autowired
18+ private User user ;
19+
20+ @ Test
21+ public void givenAutowiredAnnotation_whenSetOnField_thenRegistrarIsInjected () {
22+ assertNotNull (reg );
23+ }
24+
25+ @ Test
26+ public void givenAutowiredAnnotation_whenSetOnField_thenUserIsInjected () {
27+ assertEquals ("User1: Alice is registered" , user .register ());
28+ }
29+ }
You can’t perform that action at this time.
0 commit comments