基於上一講XML配置改造使用註解:
bean.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.hr"></context:component-scan>
<!-- 配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!-- 注入數據源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置數據源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
改造1: 項目代碼: https://github.com/2402zmybie/spring02_account_ioc_anno
至此,改造完畢, 下一講, 直接去掉配置文件bean.xml. 純註解實現配置類, 筆記:
/**
* 該類是一個配置類, 它的作用和bean.xml是一樣的
* Configuration: 指定當前類是一個配置類
* ComponentScan:
* 作用:用於通過註解指定spring在創造容器時要掃描的包
* 屬性:
* value:它和basePackages的作用是一樣的,都是用於指定創建容器時要掃描的包
* <context:component-scan base-package="com.hr"></context:component-scan>
* Bean:
* 作用: 用於把當前方法的返回值作爲bean對象存入spring的ioc容器中
* 屬性:
* name: 用於指定bean的id, 當不寫時, 默認值是當前方法的名稱
* 細節:
* 當我們使用註解配置方式時,如果方法有參數,spring框架會去容器中查找有沒有可用的bean對象,查找的方式和Autowired註解的作用一樣
* Import:
* 作用: 用於導入其他的配置類
* 屬性:
* vaule:用於指定其他配置類的字節碼, 使用Import的註解之後, 有Import註解的類就是父配置類,而導入的都是子配置類
* PropertySource:
* 作用: 用於properties文件的位置
* 屬性:
* value: 指定文件的名稱和路徑
* 關鍵字: classpath: 表示類路徑下
*/
@Configuration
@ComponentScan(value = {"com.hr"})
@Import({JdbcConfig.class})
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
項目地址: https://github.com/2402zmybie/spring02_account_annoioc_withoutxml