Comment créer des beans en .txt ?
J'ai une tâche. Je dois définir une définition de bean personnalisée. Par exemple, définissez mes beans dans un fichier txt, puis récupérez-les via le contexte d'application au Spring Boot. Je ne sais pas quoi faire. Peut-être quelqu'un peut me aider?
J'ai créé une classe : @Élément humain de classe publique {
private string name; private int age;
}
Création de beans.txt
personbean1=com.example.person personbean2=com.example.person
@config La classe publique custombeanconfig implémente 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 Application de librairie de classe publique {
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); }
}
et j'ai obtenu cette erreur : Aucun bean nommé 'personbean1' disponible
Réponse correcte
- La première solution. Vous pouvez utiliser la même approche que le fichier de configuration .xml, mais remplacer beandefinitionreader. Vous aurez le fichier de configuration :
@configuration @importresource(value = "classpath:config.txt", reader = mycustombeandefinitionreader.class) public class myconfiguration { }
et lecteur de définition de bean personnalisé :
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}; } } }
Configuration.txt :
person1=com.example.mybean person2=com.example.mybean
C'est tout. Vous obtiendrez person1 et person2.
Si vous avez des cours :
public class mybean { @autowired private mynormalservice mynormalservice; public mynormalservice getmynormalservice() { return mynormalservice; } public void setmynormalservice(mynormalservice mynormalservice) { this.mynormalservice = mynormalservice; } }
Vous pouvez tester si Spring injectera vos beans dans le service et toutes les dépendances à l'intérieur de mybean seront également gérées par Spring.
@service public class myservice { @autowired private mybean person1; @postconstruct public void test() { system.out.println("test " + person1 + " " + person1.getmynormalservice()); } }
Vous obtiendrez le résultat dans la ligne de commande :
test com.example.mybean@3343997b com.example.mynormalservice@5c1dc4e9
Veuillez noter que vous devez mettre config.txt dans le dossier ressources.
- Une autre solution simple (mais qui ne fonctionne que si vous devez définir certaines propriétés à partir du fichier 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}; } } }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

AI Hentai Generator
Générez AI Hentai gratuitement.

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)