我正在学习Spring 3,我似乎没有掌握<context:annotation-config>和<context:component-scan>背后的功能。
从我读到的内容来看,它们似乎处理不同的注释(@Required, @Autowired等vs @Component, @Repository, @Service等),但从我读到的内容来看,它们注册了相同的bean后处理器类。
更让我困惑的是,在<context:component-scan>上有一个annotation-config属性。
有人能解释一下这些标签吗?什么是相似的,什么是不同的,是一个被另一个取代,它们互相完善,我需要其中一个吗,还是两个?
Spring允许您做两件事:
自动装配bean
自动发现bean
1. Autowiring
Usually in applicationContext.xml you define beans and other beans are wired using
constructor or setter methods. You can wire beans using XML or annotations.
In case you use annotations, you need to activate annotations and you have to add
<context:annotation-config /> in applicationContext.xml. This will simplify the
structure of the tag from applicationContext.xml, because you will not have to manually wire beans (constructor or setter). You can use @Autowire annotation and the beans will be wired by type.
避免手动XML配置的一个步骤是
2. Autodiscovery
Autodiscovery is simplifying the XML one step further, in the sense that you don't even need too add the <bean> tag in applicationContext.xml. You just mark the specific beans with one of the following annotation and Spring will automatically wire the marked beans and their dependencies into the Spring container. The annotations are as follow: @Controller, @Service, @Component, @Repository. By using <context:component-scan> and pointing the base package, Spring will auto-discover and wire the components into Spring container.
作为结论:
<context:annotation-config />被使用是为了能够使用
@ autowired注解
<context:component-scan />用于确定搜索
特定的bean和自动装配的尝试。
Spring允许您做两件事:
自动装配bean
自动发现bean
1. Autowiring
Usually in applicationContext.xml you define beans and other beans are wired using
constructor or setter methods. You can wire beans using XML or annotations.
In case you use annotations, you need to activate annotations and you have to add
<context:annotation-config /> in applicationContext.xml. This will simplify the
structure of the tag from applicationContext.xml, because you will not have to manually wire beans (constructor or setter). You can use @Autowire annotation and the beans will be wired by type.
避免手动XML配置的一个步骤是
2. Autodiscovery
Autodiscovery is simplifying the XML one step further, in the sense that you don't even need too add the <bean> tag in applicationContext.xml. You just mark the specific beans with one of the following annotation and Spring will automatically wire the marked beans and their dependencies into the Spring container. The annotations are as follow: @Controller, @Service, @Component, @Repository. By using <context:component-scan> and pointing the base package, Spring will auto-discover and wire the components into Spring container.
作为结论:
<context:annotation-config />被使用是为了能够使用
@ autowired注解
<context:component-scan />用于确定搜索
特定的bean和自动装配的尝试。