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上能看到:

    恩,细细品味吧。

  • 相关阅读:
    bzoj2728
    bzoj4574
    loj2554
    bzoj1068
    bzoj2554
    Exception in thread "main" java.lang.AbstractMethodError
    java方法重载,java方法练习题
    java面向对象
    java编辑器 IntelliJ IDEA 安装——放弃过程;eclipse,Notepad++
    java二维数组
  • 原文地址:https://www.cnblogs.com/emmalai/p/4185019.html
Copyright © 2011-2022 走看看