首页 > Java > 正文

如何在.txt 中创建bean?

WBOY
发布: 2024-02-05 21:21:12
转载
973人浏览过
问题内容

我有一个任务。我需要定义一个自定义 bean 定义。例如,在txt文件中定义我的bean,然后通过spring boot中的applicationcontext检索它们。我不知道该怎么做。也许有人可以帮助我?

我创建了一个类: @成分 公共类人{

private string name;
private int age;
登录后复制

}

创建了 beans.txt

personbean1=com.example.person personbean2=com.example.person

@配置 公共类 custombeanconfig 实现 beandefinitionregistrypostprocessor {

@override
public void postprocessbeandefinitionregistry(beandefinitionregistry registry) {
    try {
        inputstream inputstream = getclass().getclassloader().getresourceasstream("beans.txt");
        bufferedreader reader = new bufferedreader(new inputstreamreader(inputstream));

        string line;
        while ((line = reader.readline()) != null) {
            string[] parts = line.split("=");

            if (parts.length == 2) {
                string beanname = parts[0].trim();
                string classname = parts[1].trim();

                registerbean(registry, beanname, classname);
            }
        }
    } catch (ioexception e) {
        e.printstacktrace();
    }
}

private void registerbean(beandefinitionregistry registry, string beanname, string classname) {
    try {
        class<?> beanclass = class.forname(classname);
        genericbeandefinition beandefinition = new genericbeandefinition();
        beandefinition.setbeanclass(beanclass);

        registry.registerbeandefinition(beanname, beandefinition);
    } catch (classnotfoundexception e) {
        e.printstacktrace();
    }
}
登录后复制

@springbootapplication 公共类 bookshopapplication {

public static void main(String[] args) {

    ConfigurableApplicationContext context = SpringApplication.run(BookShopApplication.class, args);

    Person person1 = context.getBean("personBean1", Person.class);
    Person person2 = context.getBean("personBean2", Person.class);

    System.out.println(person2);
    System.out.println(person1);
}
登录后复制

}

并出现此错误:没有名为“personbean1”的可用 bean


正确答案


  1. 第一个解决方案。您可以使用与 .xml 配置文件相同的方法,但重写 beandefinitionreader。您将拥有配置文件:
@configuration
@importresource(value = "classpath:config.txt", reader = mycustombeandefinitionreader.class)
public class myconfiguration {
}
登录后复制

和自定义 beandefinitionreader:

public class mycustombeandefinitionreader extends abstractbeandefinitionreader {

    public mycustombeandefinitionreader(beandefinitionregistry registry) {
        super(registry);
    }

    @override
    public int loadbeandefinitions(final resource resource) throws beandefinitionstoreexception {
        try {
            //take all you need from config.txt here
            string[] config = readconfig(resource.getfile()); // will return [person1='com.example.mybean', 'person2=com.example.mybean']

            beandefinitionregistry registry = getregistry();
            for (int i = 0; i < config.length; i++) {
                //get name and class
                string[] split = config[i].split("=");
                string beanname = split[0];
                string beanclass = split[1];

                //register bean definition
                genericbeandefinition beandefinition = new genericbeandefinition();
                beandefinition.setbeanclassname(beanclass);
                registry.registerbeandefinition(beanname, beandefinition);
            }

            return config.length; // amount of registered beans
        } catch (exception e) {
            throw new beandefinitionstoreexception("error while loading beans", e);
        }
    }

    public static string[] readconfig(file file) throws ioexception {
        try (bufferedreader reader = new bufferedreader(new filereader(file))) {
            string line1 = reader.readline();
            string line2 = reader.readline();
            return new string[]{line1, line2};
        }
    }
}
登录后复制

配置.txt:

person1=com.example.mybean
person2=com.example.mybean
登录后复制

就是这样。您将获得 person1 和 person2。

如果你有课:

public class mybean {
    @autowired
    private mynormalservice mynormalservice;

    public mynormalservice getmynormalservice() {
        return mynormalservice;
    }

    public void setmynormalservice(mynormalservice mynormalservice) {
        this.mynormalservice = mynormalservice;
    }
}
登录后复制

您可以测试spring是否会将您的bean注入到该服务中,并且mybean内的所有依赖项也将由spring处理。

@service
public class myservice {
    @autowired
    private mybean person1;

    @postconstruct
    public void test() {
        system.out.println("test " + person1 + " " + person1.getmynormalservice());
    }
}
登录后复制

您将在命令行中得到输出:

test com.example.mybean@3343997b com.example.mynormalservice@5c1dc4e9
登录后复制

请注意,您需要将 config.txt 放在 resources 文件夹中。

  1. 另一个简单的解决方案(但仅当您需要从 config.txt 文件设置某些属性时才有效):
@Configuration
public class MyConfiguration {

    @Bean
    public MyCustomBean myCustomBean() {
        String[] config = readConfig("path/to/your/config.txt");
        return new MyCustomBean(config[0], config[1]);
    }

    public static String[] readConfig(String filePath) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line1 = reader.readLine();
            String line2 = reader.readLine();
            return new String[]{line1, line2};
        }
    }
}
登录后复制

以上就是如何在.txt 中创建bean?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号