1. 程式人生 > 實用技巧 >9.基於Java的容器配置

9.基於Java的容器配置

9.基於Java的容器配置

這裡先直接上程式碼例子,後面會進行總結

第一步:編寫實體類

public class User implements Serializable {

@Value("xuan")
private String name;
@Value("22")
private Integer age;
....
}

第二步:編寫自己的配置類

  • @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;

@Configuration
public class XuanConfig {

@Bean
public User getUser(){
return new User();
}
}

第三步編寫測試類

  • 這裡用的是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註解原始碼

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {

/**
* Explicitly specify the name of the Spring bean definition associated with the
* {@code @Configuration} class. If left unspecified (the common case), a bean
* name will be automatically generated.
* <p>The custom name applies only if the {@code @Configuration} class is picked
* up via component scanning or supplied directly to an
* {@link AnnotationConfigApplicationContext}. If the {@code @Configuration} class
* is registered as a traditional XML bean definition, the name/id of the bean
* element will take precedence.
* @return the explicit component name, if any (or empty String otherwise)
* @see AnnotationBeanNameGenerator
*/
@AliasFor(annotation = Component.class)
String value() default "";

/**
* @since 5.2
*/
boolean proxyBeanMethods() default true;

}
  • @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;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {

/**
* {@link Configuration @Configuration}, {@link ImportSelector},
* {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
*/
Class<?>[] value();

}