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();
}