Spring 4.+ 注解的新使用方式

  今天去Spring官网上看了一下,立即被里面quick start吸引了。以往我写Spring注解都是这样:

@Autowired
private MemoryStore memoryStore;

但是demo给出的确实将注释放在构造函数上:

@Autowired
public MessagePrinter(MessageService service, SecondService second) {
        this.service = service;
        this.second = second;
    }

最后的调用也很方便,都没有用到任何xml文件(容器):

 1 @Configuration
 2 @ComponentScan
 3 public class Application {
 4 
 5     private static ApplicationContext context;
 6     private int i = 5;
 7     
 8     @Bean
 9     MessageService mockMessageService() {
10         return new MessageService() {
11             
12             public String getMessage() {
13                 return "Happy Christmas";
14             }
15         };
16     }
17     
18     @Bean
19     SecondService mockSecondService() {
20         return new SecondService() {
21             
22             public int getCount() {
23                 return ++i;
24             }
25         };
26     }
27     
28     public static void main(String args[]) {
29         context = new AnnotationConfigApplicationContext(Application.class);
30         MessagePrinter printer = context.getBean(MessagePrinter.class);
31         printer.printMessage();
32         
33     }
34 }

觉得以后的单元测试可使用这种方法,就不用因启动一个容器而初始化不必要的bean了,还蛮cool的。

另外,Oliver Gierke给的解释也在StackOverFlow上能看到:

恩,细细品味吧。

原文地址:https://www.cnblogs.com/emmalai/p/4185019.html