手动配置springboot的bean

这是一个关于Spring Boot应用程序的示例,展示了如何通过`@ConfigurationProperties`和`@PropertySource`注解从配置文件中注入用户属性。在主类`SpringbootApplication`中,程序启动时获取并打印了配置的用户信息。用户类`User`包含了用户ID、用户名、密码和性别等字段。
摘要由CSDN通过智能技术生成

测试

package com.sky.springboot;

import com.sky.springboot.pojo.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(SpringbootApplication.class, args);
        User user = (User) run.getBean("user");
        System.out.println("user:"+user);

    }

}

pojo

package com.sky.springboot.pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "user")
@PropertySource(value = "classpath:config.properties")
public class User {

    private int userid;
    private String uname;
    private String upwd;
    private String sex;

    @Override
    public String toString() {
        return "User{" +
                "userid=" + userid +
                ", uname='" + uname + '\'' +
                ", upwd='" + upwd + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUpwd() {
        return upwd;
    }

    public void setUpwd(String upwd) {
        this.upwd = upwd;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public User() {
    }

    public User(int userid, String uname, String upwd, String sex) {
        this.userid = userid;
        this.uname = uname;
        this.upwd = upwd;
        this.sex = sex;
    }
}

配置

user.userid=100
user.uname=kkk
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值