1. 程式人生 > >Spring學習之路 -- Java配置

Spring學習之路 -- Java配置

Java配置是Spring4.x推薦的配置方式,可以完全替代xml配置

Java配置是通過@Configuration和@Bean來實現的

  • @Configuration聲明當前類是一個配置類,相當於一個Spring配置的xml檔案
  • @Bean註解在方法上,聲明當前方法的返回值為一個Bean

示例

(1)編寫功能類的Bean

package com.ch1.javaconfig;

public class FunctionService {
    public String sayHello(String str) {
        return "Hello " + str + "!";
    }
}

(2)使用功能類的Bean

package com.ch1.javaconfig;

public class UseFunctionService {
    FunctionService functionService;

    public void setFunctionService(FunctionService functionService) {
        this.functionService = functionService;
    }

    public String sayHello(String str) {
        return functionService.sayHello(str);
    }
}

(3)配置類

package com.ch1.javaconfig;

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

//使用@Configuration註解表明當前類是一個配置類,說明這個類裡可能有0個或多個@Bean註解。
//沒有使用@ComponentScan是因為所有的Bean都在類中定義了

@Configuration  
public class JavaConfig {
    @Bean   //使用@Bean註解聲明當前方法返回值是一個Bean,Bean的名稱是方法名
    public FunctionService functionService() {
        return new FunctionService();
    }

    @Bean
    public UseFunctionService useFunctionService() {
        UseFunctionService useFunctionService = new UseFunctionService();
        useFunctionService.setFunctionService(functionService());
        return useFunctionService;
    }
}

(4)執行

package com.ch1.javaconfig;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
        UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);

        System.out.println(useFunctionService.sayHello("admin"));

        context.close();
    }
}

(5)結果