用一个java类代替xml文件来配置spring 的注入,这种方式经常在springboot 中使用
1.编写pojo实体类,并且加上注解

package pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这个注解是指将User这个类注入到spring 容器中,即是说这个类由spring托管了,
//这个注释相当于<bean id="user" class="pojo.User">
@Component
public class User {
    private Integer id;
    //@Value 是为name 注入值,相当于xml中的<property name="name" value="xiaobin"></property>
    @Value("xiaobin")
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }
}
2.编写自己的javaconfig类
package myconfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import pojo.User;
import java.lang.reflect.Proxy;
//加了这个Configuration注解后,这个java文件就相当于我们写的applicationContext.xml文件
@Configuration
//ComponentScan这个注解是扫描pojo包
@ComponentScan("pojo")
public class XiaobConfig {
    @Bean
    //这里是相当于在xml写一个bean,比如<bean id="user" class="pojo.User">
    public User getUser(){
        return  new User();
    }
}
3.编写测试类(xml就不需要再写了)
package test;
import myconfig.XiaobConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import pojo.User;
public class Mytest {
    public static void main(String[] args) {
        //这个方法是去获取config类文件的
        ApplicationContext applicationContext=new AnnotationConfigApplicationContext(XiaobConfig.class);
        User user= (User) applicationContext.getBean("getUser");
        System.out.println(user);
    }
}
输出的结果是:
User{id=null, name=‘xiaobin‘}
spring 注入的方式(javaconfig常用于springboot)
原文:https://www.cnblogs.com/codinggege/p/13599615.html