Spring Framework tutorial


学习maven

pom.xml <packaging> <artifactId>

<dependencies>
compile package install


 

 spring dependency injection 使用实例

<artifactId>spring-context</artifactId>

1 package hello;
2 
3 public interface MessageService {
4     String getMessage();
5 }
 1 package hello;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Component;
 5 
 6 @Component
 7 public class MessagePrinter {
 8 
 9     final private MessageService service;
10 
11     @Autowired
12     public MessagePrinter(MessageService service) {
13         this.service = service;
14     }
15 
16     public void printMessage() {
17         System.out.println(this.service.getMessage());
18     }
19 }

 

 1 package hello;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.annotation.*;
 5 
 6 @Configuration
 7 @ComponentScan
 8 public class Application {
 9 
10     @Bean
11     MessageService mockMessageService() {
12         return new MessageService() {
13             public String getMessage() {
14               return "Hello World!";
15             }
16         };
17     }
18 
19   public static void main(String[] args) {
20       ApplicationContext context = 
21           new AnnotationConfigApplicationContext(Application.class);
22       MessagePrinter printer = context.getBean(MessagePrinter.class);
23       printer.printMessage();
24   }
25 }

 

posted @ 2015-05-07 19:08  JosephLiao  阅读(255)  评论(0编辑  收藏  举报