简体   繁体   English

使用Spring分配域类的数据成员

[英]Assign data member of a domain class using Spring

Is it possible? 可能吗?

Here is a more detailed case: 这是更详细的情况:

class A {
    private service x;

    //other members
    //some more methods.
}

bean definition is available for service but I do not want class A to be a spring bean and neither x to be static. bean定义可用于service但我不希望class A是spring bean,也不希望x是静态的。

Is this achievable. 这是可以实现的。

EDIT: 编辑:

My spring configuration: 我的弹簧配置:

<bean id="Service" class="com.xx.yy.Service" />
<--!I do not register class A as a bean. Hence cannot use @autowired directly.-->

I think you should create the factory for instances of class A which should take care of setting x. 我认为您应该为类A的实例创建工厂,该工厂应注意设置x。

@Service
class FactoryA {

  @Autowired service x;

  public A create() {
    return new A(x);
  }

}

It can only be achieved by manually getting the bean from the context. 这只能通过从上下文手动获取Bean来实现。

Service service = context.getBean(Service.class);
A a = new A(service);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Boot - 从 YML 文件中为类成员赋值 - 空指针异常 - Spring Boot - Assign value to Class Member from YML file - Null Pointer Exception Spring数据JPA:按自定义class类型成员的列查找 - Spring data JPA: find by column of custom class type's member 如何检索给定域 class 的 spring 数据存储库实例? - How to retrieve spring data repository instance for given domain class? 如何使用 lombok 为实体中嵌入类的成员变量分配默认值? - How to assign default value to the member variable of embedded class in an entity using lombok? 如何使用Spring Data Cassandra将域对象映射到CQL表? - How to map domain objects to CQL Tables using Spring Data Cassandra? 如何在 spring 中使用依赖注入将类属性传递值分配给类构造函数? - How to assign a class property passing value to class constructor using Dependency injection in spring? 使用ClassPathXmlApplicationContext创建spring数据连接类 - creating a spring data connection class using ClassPathXmlApplicationContext Spring JPA存储库findBy直接通过外键使用POJO代替类的数据成员 - Spring JPA Repository findBy foreign key directly with POJO instead of data member of class 使用与Spring Boot和Spring Data JPA相同的域模型的多个数据库 - Multiple databases using same domain models with Spring Boot and Spring Data JPA java嵌套类的数据成员 - java nested class data member
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM