Spring5.0的第一次嘗鮮


對於這次嘗鮮,說白了和Spring5.0的新特性基本沒有多大的關系,如果說您不小心進來了,卻發發現文章的內容和標題似乎不太匹配,那么我將是非常的抱歉,因為這浪費了您寶貴的時間。但是我還是要說:因為這確實是Spring5.0中的一個demo.而我在這里寫下這個Demo的原因是這個Demo全部是注解的配置,因為我的習慣還停留在XML的階段。 
好了,讓我們引入context包吧,這里使用maven配置:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.0.RELEASE</version>
    </dependency>
</dependencies>

這個Demo的實現思路是這樣的,首先我們定義一個接口,定義一個類,該類要調用該接口中的方法,但是又沒有實現這個接口,此時我們可以考慮下怎么做呢?很簡單的,在不涉及其他類的情況下貌似只能在該類中的該方法中使用匿名內部類的方式的完成,但是這和我們之前的說的是一致的,我們要解耦,就要注入。這個Demo說的就是注入。在該Demo中,這個類將該接口私有化並且最終化,以便是有構造器注入。然后在方法中直接調用即可。在配置類中使用匿名內部類的方式創建這個接口的bean。在main方法中首先加載配置類,獲取上下文,然后用上下文調用方法所在的類,進而調用方法。其實真正的方法的執行體應該是接口的匿名實現類的方法。

package hello;

public interface MessageService {
    String getMessage();
}


package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessagePrinter {
    /**
     * 定義私有的,最終的成員變量,並且使用構造器進行初始化
     */
    final private MessageService service;

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

    public void printMessage(){
        System.out.println(service.getMessage());
    }
}



package hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class Application {
    @Bean
    MessageService mockMessageService(){
        return new MessageService() {
            public String getMessage() {
                return "Hello World!";
            }
        };
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        MessagePrinter printer = context.getBean(MessagePrinter.class);
        printer.printMessage();//Hello World!
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM