9.基于Java的容器配置
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;

浙公网安备 33010602011771号