使用JavaConfig实现配置

2022/1/6 17:37:44

本文主要是介绍使用JavaConfig实现配置,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!


完全不使用Spring的xml,全部交给Java来做,在Springboot中很常见


User.java:

package com.kakafa.pojo;

import org.springframework.beans.factory.annotation.Value;

public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("许魏洲")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}


KakafaConfig:

package com.kakafa.config;

import com.kakafa.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KakafaConfig {

    @Bean
    public User getUser(){
        return new User();
    }
}

test:

import com.kakafa.config.KakafaConfig;
import com.kakafa.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(KakafaConfig.class);//注意这里不加双引号
        User getUser = (User)context.getBean("getUser");
        System.out.println(getUser.getName());


    }
}


这篇关于使用JavaConfig实现配置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程