1. 程式人生 > 實用技巧 >Spring基於註解的配置 - 基於 Java 的配置

Spring基於註解的配置 - 基於 Java 的配置

Spring 中為了減少 XML 配置,可以宣告一個配置類類對 bean 進行配置,主要用到兩個註解 @Configuration 和 @bean,例子:

首先,XML 中增加如下的配置來啟動 java 配置:

<context:component-scan base-package = "com.shiyanlou.demo.config"/>

定義一個配置類,用 @Configuration 註解該類,等價於 XML 裡的 beans,用 @Bean 註解方法,等價於 XML 配置的 bean,方法名等於 bean Id。建立包 com.shiyanlou.demo.config,然後依次建立 SpringConfig.java、Service.java 和 Client.java,程式碼如下:
SpringConfig.java:

package com.shiyanlou.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {

    @Bean
    public Service service(){
        return new Service();
    }
    @Bean
    public Client client(){
        return new Client();
    }
}

Service.java:

package com.shiyanlou.demo.config;

public class Service {
    public String  sayHello(){
        return "HelloWord!";
    }
}

Client.java:

package com.shiyanlou.demo.config;

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

public class Client {
    @Autowired
    Service service;
    public void invokeService(){
        System.out.println("client invoke :" + service.sayHello());
    }

}

最後修改 App.java 的程式碼:

package com.shiyanlou.demo;

import com.shiyanlou.demo.config.Client;
import com.shiyanlou.demo.config.SpringConfig;
import com.shiyanlou.demo.helloworld.HelloWorld;
import com.shiyanlou.demo.entity.Dog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class App {

    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        Client client = context.getBean("client", Client.class);
        client.invokeService();
    }
}

執行

mvn compile
mvn exec:java -Dexec.mainClass="com.shiyanlou.demo.App"

實驗結果如下所示: