简体   繁体   中英

Inject inherited property values using CDI-Weld

I'm developing a basic Swing application and, even if I always tend to use Spring Ioc (with xml configuration) for dependency injection I want to give a try to CDI-Weld. Having the following structure done in Spring, the container creates a SchoolBoy and a UniversityStudent , each one with its name.

public class Student{

    protected String name;

    public void setName(String name){
        this.name = name;
    }

}

public class SchoolBoy extends Student{

}

public class UniversityStudent extends Student{

}
<bean class="SchoolBoy">
    <property name="name" value="Daniel" />
</bean>

<bean class="UniversityStudent">
    <property name="name" value="Rose" />
</bean>

I've seen it's possible to do something similar in CDI using @Inject @Config annotations. However, every single time I see this, they're above the property itself and, being an inherited property, I cannot do that for my classes here. How do I achieve each Student subclass to get its own name value?

UPDATE

Injecting that values in subclasses doesn't necessarily mean hardcoding them in the configuration file. The property value itself can be acquired from a .properties file. However given the edge case that Student is into a legacy project and I want to innherit my classes from it and inject that property, what could the solution be?

CDI currently doesn't support XML configuration natively. You have to use a library like Solder to achieve this. However it's a bad practice and strongly discouraged to set bean properties where you configure your dependency management (spring.xml) as this is not type and refactor safe. The other option is to use a producer method where you will set the needed value:

public SchoolBoy produceSchoolBoy {
   //construct new SchoolBoy() and set its name
}

and you will have a producer for the different Student types. Not very flexible but will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM