Spring Bean配置有以下三種形式:
- 傳統的xml配置
- Spring 2.5 以后新增注解配置
- Spring3.0以后新增JavaConfig
1. 傳統的xml配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="helloWorld" class="com.example.whx.HelloWorld"/> </beans>
2.基於注解的配置
@Component是Spring容器的基本注解,表示容器中的一個Bean組件。使用@Comopnent相當於代替了XML配置中的<bean>元素
HelloWorld.java
package annotationConfig; import org.springframework.stereotype.Component; /** * 如果屬性名稱是value,value可以省略。 * 如果不指定value,默認值是類名首先字母變為小寫。 * @Component(value="beanId") 就是把當前類實例化。相當於<bean id="beanId"> */ @Component public class HelloWorld { public void sayHello() { System.out.println("Hello World"); } }
Spring在2.5后提供了一個context的命名空間,它提供了通過掃描類包來加載使用注解定義的bean的方式。
<!-- 開啟注解掃描 -->
<context:component-scan base-package="com.example.annotationconfig"/>
Spring2.5 添加了對JSR250注解的支持,有@Resource @PostConstruct @ PreDestroy
自動裝配注解
Spring自帶的@AutoWired
JSR250的@Resource注解
JSR330的@Inject注解
Spring容器是默認禁用注解裝配的。要使用基於注解的自動裝配,我們在xml文件中配置:
<context:annotation-config>
使用<context:annotation-config>相當於代替了xml配置的<property>和<constructor-arg>元素
<context:comoponent-scan>除了包含<context:annotatiion-config>的作用外,還能自動掃描和注冊base-package下@Component注解的類,將其bean注冊到spring容器里,所以配置文件如果有component-scan就不需要annotation-config
3.基於java config
通過java類定義spring配置元數據,且直接消除xml配置文件
Spring3.0基於java的配置直接支持下面的注解:
@Configuration
@Bean
@DependsOn
@Primary
@Lazy
@Import
@ImportResource
@Value
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
測試類,查看配置是否成功:
public class Test { public static void main(String[] args) { //加載配置 ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); MyService myService = ctx.getBean(MyService.class); myService.sayHello(); } }
