这里先直接上代码例子,后面会进行总结java
第一步:编写实体类spring
public class User implements Serializable {
第二步:编写本身的配置类数组
@Configuration:这个注解至关于标志了这个类是一个配置类 就像咱们applicationConfig.xml配置文件的beans标签app
@Bean :见名知意 至关于xml中的bean标签 将对象添加到容器中 测试
getUser(方法名):至关于bean标签中的id属性atom
User(返回值类型): 至关于bean标签中的饿class属性spa
package com.xuan.config;
import com.xuan.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
第三步编写测试类code
这里用的是AnnotationConfigApplicationContext也就是注解版的上下文component
AnnotationConfigApplicationContext中的参数是传一个咱们本身配置类的字节码文件(能够是多个可是通常咱们不这样写,咱们会将多个配置类经过@Import方法添加在主配置类中)xml
下面的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;