zoukankan      html  css  js  c++  java
  • 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上能看到:

    恩,细细品味吧。

  • 相关阅读:
    多线程
    泛型
    枚举、注解
    重写comparater比较器
    Arrays工具类和Collections工具类
    重写equals和hashCode的方法
    遍历集合的方法
    关键字总结
    having 的用法
    HTTP协议
  • 原文地址:https://www.cnblogs.com/emmalai/p/4185019.html
Copyright © 2011-2022 走看看