如何在.txt 中创建bean?

问题内容

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

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

private string name;private int age;

登录后复制

}

创建了 beans.txt

personbean1=com.example.personpersonbean2=com.example.person

@配置公共类 custombeanconfig 实现 beandefinitionregistrypostprocessor {

@overridepublic 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

正确答案

第一个解决方案。您可以使用与 .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 

配置.txt:

person1=com.example.mybeanperson2=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处理。

@servicepublic 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 文件夹中。

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

@Configurationpublic 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?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2622035.html

(0)
上一篇 2025年3月6日 23:43:06
下一篇 2025年2月19日 07:02:42

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论