9.基於Java的容器配置
阿新 • • 發佈:2020-07-16
9.基於Java的容器配置
這裡先直接上程式碼例子,後面會進行總結
第一步:編寫實體類
public class User implements Serializable {
第二步:編寫自己的配置類
-
@Configuration:這個註解相當於標誌了這個類是一個配置類 就像我們applicationConfig.xml配置檔案的beans標籤
-
@Bean :見名知意 相當於xml中的bean標籤 將物件新增到容器中
-
getUser(方法名):相當於bean標籤中的id屬性
-
User(返回值型別): 相當於bean標籤中的餓class屬性
package com.xuan.config;
import com.xuan.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
第三步編寫測試類
-
這裡用的是AnnotationConfigApplicationContext也就是註解版的上下文
-
AnnotationConfigApplicationContext中的引數是傳一個我們自己配置類的位元組碼檔案(可以是多個但是一般我們不這樣寫,我們會將多個配置類通過@Import方法新增在主配置類中)
-
下面的getBean方法傳入的引數可以是傳入id,沒傳的話會spring會自動掃描配置
import com.xuan.config.XuanConfig;
import com.xuan.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestUser {
public static void main(String[] args) {
ApplicationContext context=new AnnotationConfigApplicationContext(XuanConfig.class);
User user = context.getBean(User.class);
System.out.println(user);
}
}
補充
-
@Configuration註解原始碼
-
@Import註解原始碼 :發現是可以傳入陣列的配置類的
package org.springframework.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;