目录
正确答案
首页 Java 如何在.txt 中创建bean?

如何在.txt 中创建bean?

Feb 05, 2024 pm 09:21 PM

问题内容

我有一个任务。我需要定义一个自定义 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 文件夹中。

  • 另一个简单的解决方案(但仅当您需要从 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中文网其他相关文章!

    本站声明
    本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

    热AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智能驱动的应用程序,用于创建逼真的裸体照片

    AI Clothes Remover

    AI Clothes Remover

    用于从照片中去除衣服的在线人工智能工具。

    Undress AI Tool

    Undress AI Tool

    免费脱衣服图片

    Clothoff.io

    Clothoff.io

    AI脱衣机

    AI Hentai Generator

    AI Hentai Generator

    免费生成ai无尽的。

    热门文章

    R.E.P.O.能量晶体解释及其做什么(黄色晶体)
    1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.最佳图形设置
    1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
    威尔R.E.P.O.有交叉游戏吗?
    1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

    热工具

    记事本++7.3.1

    记事本++7.3.1

    好用且免费的代码编辑器

    SublimeText3汉化版

    SublimeText3汉化版

    中文版,非常好用

    禅工作室 13.0.1

    禅工作室 13.0.1

    功能强大的PHP集成开发环境

    Dreamweaver CS6

    Dreamweaver CS6

    视觉化网页开发工具

    SublimeText3 Mac版

    SublimeText3 Mac版

    神级代码编辑软件(SublimeText3)