【Spring】使用JavaConfig實現配置

不使用Spring的XML配置,全權交給java來做!
JavaConfig是Spring的一個子項目,在Spring4之後,它稱爲了Spring的核心功能!
實體類

package com.lrx.poji;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//說明這個類被Spring註冊到了容器中
@Component
public class User {
  @Value("lixin")
  private String name;

  public String getName() {
      return name;
  }

  public void setName(String name) {
      this.name = name;
  }

  @Override
  public String toString() {
      return "User{" +
              "name='" + name + '\'' +
              '}';
  }
}

配置文件

package com.lrx.config;

import com.lrx.poji.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//這個也會被Spring容器託管,因爲它本來就是一個@Component
// @Configuration代表一個類,就和我們之前的ApplicationContext.xml是一樣的
@Configuration
@ComponentScan("com.lrx.poji")
public class LiConfig {
    //註冊一個bean,就相當於xml寫的一個bean標籤
    //這個方法的名字就相當於bean標籤中的ID屬性
    //方法的返回值相當於bean標籤中的class屬性
    @Bean
    public User getUser(){
        return new User();   //就是要注入到bean的對象
    }
}

測試類

import com.lrx.config.LiConfig;
import com.lrx.poji.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置類方式去做,我們就只能通過AnnotationConfig上下文來獲取容器
        // 然後通過配置類的class對象來加載!
        ApplicationContext context=new AnnotationConfigApplicationContext(LiConfig.class);
        User getUser= (User) context.getBean("user");
        System.out.println(getUser.getName());
    }
}

這種純Java的配置方式在Spring Boot中隨處可見!

發佈了9 篇原創文章 · 獲贊 6 · 訪問量 631
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章