2

我想知道我是否在属性上添加了 @Value 注释,包含此属性的类不能被另一个具有不同值的类使用,例如:

MyClassUtil.java 有

@Value("${some.value}")
private int _myProperty;

当然还有一个 module.properties 包含:

some.value=10

另一个类 ClassA.java 想使用这个值为 10 的类。好的,没问题。但是另一个类 ClassB.java 想要使用这个类,但具有另一个值:20。如果我没记错的话,我不能这样做。因为在@Value 时代之前,我可以毫无问题地在moduleContext.xml 中声明两个bean。

那么,@Value 是否会促使您进行一些强耦合?

4

1 回答 1

2

You are right that the annotation configuration can not be instance specific. It is important to understand the concept of bean definitions in bean factory.

Manual bean definition:

  • Single <bean> element in your XML config leads to a single bean definition. Multiple <bean> mean multiple definitions (regardless of a bean type).
  • Single @Bean method within @Configuration class leads to a single bean definition. Multiple @Bean methods mean multiple definitions (regardless of a bean type).

However when using component scan, classes annotated with @Component-like annotations are auto-registered as a single bean definition. There is no way you can register bean multiple times via component scan.

Similarly, annotation configurations (@Value, @Autowired, etc.) are type-wide. Your bean instances are always augmented and processed with the same effect (e.g. injecting the same value). There is no way you can alter annotation processing behaviour from instance to instance.

Is this tight coupling? It is not in its general understanding - bean factory (Spring) is still free to inject whatever it thinks is suitable. However it is more of a service lookup pattern. This simplifies your life when working with domain specific singletons. And most beans in an application context tend to be singletons, many of them domain specific (controllers, services, DAOs). Framework singletons (non-project specific reusable classes) should never use annotation based configuration - in this scope, it is an unwanted tight coupling.

If you need different bean instances, you should not use annotation configuration and define your beans manually.

于 2013-06-14T15:22:10.987 回答