0

0

如何在.txt 中创建bean?

WBOY

WBOY

发布时间:2024-02-05 21:21:12

|

1050人浏览过

|

来源于stackoverflow

转载

问题内容

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

易优cms汽车车辆租赁源码1.7.2
易优cms汽车车辆租赁源码1.7.2

由于疫情等原因大家都开始习惯了通过互联网上租车服务的信息多方面,且获取方式简便,不管是婚庆用车、旅游租车、还是短租等租车业务。越来越多租车企业都开始主动把租车业务推向给潜在需求客户,所以如何设计一个租车网站,以便在同行中脱颖而出就重要了,易优cms针对租车行业市场需求、目标客户、盈利模式等,进行策划、设计、制作,建设一个符合用户与搜索引擎需求的租车网站源码。 网站首页

下载
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};
        }
    }
}

相关标签:

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

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

102

2025.08.06

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

135

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

389

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

68

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

32

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

114

2025.12.24

pdf怎么转换成xml格式
pdf怎么转换成xml格式

将 pdf 转换为 xml 的方法:1. 使用在线转换器;2. 使用桌面软件(如 adobe acrobat、itext);3. 使用命令行工具(如 pdftoxml)。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

1875

2024.04.01

xml怎么变成word
xml怎么变成word

步骤:1. 导入 xml 文件;2. 选择 xml 结构;3. 映射 xml 元素到 word 元素;4. 生成 word 文档。提示:确保 xml 文件结构良好,并预览 word 文档以验证转换是否成功。想了解更多xml的相关内容,可以阅读本专题下面的文章。

2085

2024.08.01

Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

36

2026.01.14

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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