首页 > 编程语言 > 详细

spring 注入的方式(javaconfig常用于springboot)

时间:2020-09-02 08:47:52      阅读:92      评论:0      收藏:0      [点我收藏+]

用一个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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!