java - Spring - 使用@Configurable 和@Value 注释用新运算符创建对象

标签 java spring properties dependency-injection aspectj

是否可以在使用 AspectJ 编织的类上使用 @Configurable 并让 Spring 在用 @Value 注释的字段/方法上加载值?

我知道可以使用@Autowired 和@Resource 等...还有其他的吗?

例如

@Configurable
public Class MyObj{
 @Value("$(my.prop)")
 private String aField;

 public String getAField(){
   return aField;
 }
}

然后有类似的东西

public aMethodSomewhereElse(){
   MyObj obj = new MyObj()
   assertNotNull(obj.getAField());
}

除了能够使用 new 运算符创建 MyObj 并且仍然使用 spring 来处理注释之外,是否有任何替代方法?

--编辑:--

在使用@Autowired 时可以使用 new 来做到这一点,看看一些 Hibernate 和 JPA 与 Spring 和 AOP 的东西...我用过这在过去对 Java 代码做了一些分析。但我真的很想在模拟完整示例之前使用 SPEL 和 @Value 我希望在这里找到答案。仅供引用 - 如果你不相信我,Spring Manual 甚至说可以这样做,我想知道的是是否可以在同一范围内使用 @Value 注释......

The Spring container instantiates and configures beans defined in your application context. It is also possible to ask a bean factory to configure a pre-existing object given the name of a bean definition containing the configuration to be applied. The spring-aspects.jar contains an annotation-driven aspect that exploits this capability to allow dependency injection of any object.

还有……

Using the annotation on its own does nothing of course. It is the AnnotationBeanConfigurerAspect in spring-aspects.jar that acts on the presence of the annotation. In essence the aspect says "after returning from the initialization of a new object of a type annotated with @Configurable, configure the newly created object using Spring in accordance with the properties of the annotation". In this context, initialization refers to newly instantiated objects (e.g., objects instantiated with the 'new' operator) as well as to Serializable objects that are undergoing deserialization (e.g., via readResolve()).

http://static.springsource.org/spring/docs/3.0.0.RC2/reference/html/ch07s08.html

干杯。

最佳答案

你完全正确 - @Autowired 字段将被连接到一个 @Configurable 注释类中,即使在 Spring 容器之外,假设你有一个 AspectJ 基础设施.

虽然您已经注意到一个很好的问题,@Value 字段由 Spring bean 后处理器 (AutowiredAnnotationBeanPostProcessor) 处理,它解析 @Value 注释字段。它不会作用于在容器外部实例化的对象 - 所以简而言之,@Autowired 字段应该被连接,但 @Value 属性不会。

关于java - Spring - 使用@Configurable 和@Value 注释用新运算符创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15106163/

相关文章:

java - Spring在运行时添加占位符值

java - 如何使用流利的Apache Components

java - Spring MVC 资源映射

javascript - 如何获取javascript类属性列表

java - 是否可以在编辑 Spring XML 文件时检查该类是否存在?

java - 如何使用 Spring Data Cassandra 仅查询 1 个字段?

C# - 常量属性是否等同于 lambda 表达式?

java - 杜克快速重复数据删除 : java. lang.UnsupportedOperationException : Operation not yet supported?

java - 在 IntelliJ Idea 中,我的应用程序可以运行,但作为 jar 运行——不是因为 "Error: Could not find or load main class"

java - 使用 java 的 native 方法