首页  >  文章  >  如何在.txt 中创建bean?

如何在.txt 中创建bean?

WBOY
WBOY转载
2024-02-05 21:21:12811浏览
问题内容

我有一个任务。我需要定义一个自定义 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中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除