-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSpringSetterAutowired.java
More file actions
53 lines (45 loc) · 1.64 KB
/
SpringSetterAutowired.java
File metadata and controls
53 lines (45 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Setter DI injection Hello World using Java annotation
*
* Created by vvedenin on 11/14/2015.
*/
public class SpringSetterAutowired {
public static class Notifier {
private NotificationService service;
@Autowired
public void setService(NotificationService service) {
this.service = service;
}
public void send(String message) {
service.send("email: " + message);
}
}
public static class EMailService implements NotificationService {
public void send(String message) {
System.out.println("I send " + message);
}
}
public interface NotificationService {
void send(String message);
}
@Configuration
public static class DIConfiguration {
@Bean
public Notifier getNotifier(NotificationService service){
return new Notifier();
}
@Bean
public NotificationService getNotificationService(){
return new EMailService();
}
}
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DIConfiguration.class);
Notifier notifier = context.getBean(Notifier.class);
notifier.send("Hello World!"); // Print "I send email: Hello World!"
}
}