數據庫連接池的XML配置
此處我用的是c3p0連接池,導入外部的數據庫配置文件
<context:property-placeholder location="classpath:jdbc.properties">
</context:property-placeholder>
<bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
Spring的IOC和依賴注入註解配置
@Component("bean的id值") 定義在類上 只要定義在了類上
那麼註解掃描器只要一掃描到就會創建該類的實例對象 放在spring容器中
現在都是使用這個註解所衍生的三個註解
@Controller("bean的id值") 針對的就是web層
@Service("bean的id值") 針對的是service層
@Repository("bean的id值") 針對的是dao層
@Scope("singleton"或則prototype) 定義在類上的 指定當前類是單實例還是多實例
將其放到類的上方即可,如不指定bean的id值,則默認爲方法名的首字母小寫的名稱
@Repository
public class PersonDaoImpl implements PersonDao{}
@Service
public class PersonServiceImpl implements PersonService{}
接下來就是數據的依賴注入
@Value("屬性值") 定義在屬性字段上 針對的是基本類型和String類型
如果使用了這個註解 該屬性的set方法可以省略不寫
@Autowired 定義在屬性字段上的 針對的是對象類型
如果定義在了那個對象類型的屬性身上 會自動去spring容器中找該類型的實例對象給賦值,當容器中
存在多個該類型的實例對象時會報錯,這是需要和下面這個註解配合使用
@Qualifier("bean的id值")定義在屬性字段上的 指定用該類型的哪個id名稱的實例對象
注意: @Qualifier要想使用 必須結合 @Autowired 一起使用
@Resource("bean的id值")是@Autowired和@Qualifier倆註解的功能和
@PostConstruct 初始化執行的方法,放在方法上
@PreDestroy 銷燬時執行的方法,放在方法上
@Value("3")
private Integer id;
@Autowired
// @Qualifier("personDaoImpl")
private PersonDao personDao;
@Override
public void save() {
personDao.save();
}
@PostConstruct //初始化執行的方法
public void init() {
System.out.println("PersonServiceImpl創建了");
}
@PreDestroy //銷燬時執行的方法
public void destory() {
System.out.println("PersonServiceImpl銷燬了");
}
Spring的註解配置文件和數據庫連接池的註解配置
@Configuration //註解配置類
@ComponentScan(value="service,dao") //配置要掃描的包,掃描多個包用逗號隔開
@PropertySource(value="classpath:jdbc.properties") //配置要加載的外部文件
public class SpringConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name="c3p0")
public DataSource createDataSource() throws Exception {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
// Spring在4.3版本之前要配置此解析器,否則無法識別${},4.3及以後的版本不需要配置
@Bean
public static PropertySourcesPlaceholderConfigurer createPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
此文章爲我個人的學習筆記總結,自用