我很想知道这样的代码有什么区别:
class MyClass {
@Autowired
MyService myService;
}
和这样的代码:
class MyClass {
MyService myService;
@Required
public void setMyService(MyService val) {
this.myService = val;
}
}
@Autowired
当您想要自动装配 bean 时使用注释。@Autowired
不限于setter。它也可以与构造函数和字段一起使用。如果您@Autowired
在字段上使用注释,则该字段将与具有匹配数据类型的 bean 自动装配。
@Required
检查是否已设置特定属性。如果一个字段已经被@Required
注解并且该字段没有被设置,你会得到org.springframework.beans.factory.BeanInitializationException
.
参考:
编辑:正如'kryger'所指出的:用注释的字段@Autowired
也有效@Required
(除非您明确将其参数设置为false)。例如:
@Autowired(required=false)
private ObjectType objectType;
对于已经注释的字段@Autowired
,如果匹配数据类型的 bean 不可用,org.springframework.beans.factory.BeanCreationException
则抛出。
@Autowired
不一样@Required
。
-Annotation (如您的代码示例中@Autowire
所示)告诉 ApplicationContext(又名 Spring-IoC-Containter)注入所需的依赖项。(无论如何,如果它使用注释或 ApplicationContext 的 XML 文件)。
-Annotation@Required
告诉 ApplicationContext 必须在 XML 文件(ApplicationContext 的 XML 文件)中提及此属性,这会导致使用 XML 文件注入依赖项(或者当然是期望)。但是注释本身并没有告诉注入依赖! 注入已完成,因为 XML 文件中提到了该属性。 很高兴知道,您可能需要它。
提到 XML 文件中的属性,我的意思是这样的配置,例如:
<bean id="MyClass" class="com.myclasses.common.MyClass">
<property name="someProperty" value="ValueThatHasToBeInjected" />
</bean>
那么我为什么要在@Autowired-Annotation 上使用它呢?
当依赖项必须通过 XML 配置文件中的信息注入时,您应该使用它。
能给我举个例子?
嗯,这个网站上已经有一个很好的例子。这也解释了。
@watchme @Required -annotation 告诉容器该属性需要作为配置的一部分进行初始化,它可以通过 xml 配置或通过 @Autowired 注释或通过创建 java bean 来初始化。
xml 示例:
public class SimpleMovieLister
{
private MovieFinder movieFinder;
@Required
public void setMovieFinder(MovieFinder movieFinder)
{
this.movieFinder = movieFinder;
}
}
<beans ...>
<bean id = "movieFinder" class = "com.test.MovieFinder">
<bean id = "simpleMovieLister" class = "com.test.SimpleMovieLister">
<property name = "movieFinder" value = "movieFinder" />
通过@Autowire
public class SimpleMovieLister
{
@Autowired
@Required
private MovieFinder movieFinder;
}
这里说真的我们不需要@Required,因为它@Autowired 默认是必需的。
通过@Bean
public class SimpleMovieLister
{
private MovieFinder movieFinder;
@Required
public void setMovieFinder(MovieFinder movieFinder)
{
this.movieFinder = movieFinder;
}
}
public class AppConfig {
@Bean
public SimpleMovieLister getSimpleMovieLister()
{
SimpleMovieLister simpleMovieLister = new SimpleMovieLister();
simpleMovieLister.setMovieFinder(new MoveFinder());
}
}