spring三: 装配bean( 在xml中进行显式配置, 在java中进行显式配置)
生活随笔
收集整理的這篇文章主要介紹了
spring三: 装配bean( 在xml中进行显式配置, 在java中进行显式配置)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class); SpringConfiguration配置類作為類AnnotationConfigApplicationContext的參數(shù),那么SpringConfiguration就可以省略@Configuration. 如下
//@Configuration @ComponentScan(basePackages = {"com.atchina"}) public class SpringConfiguration {}?
在java中進(jìn)行顯式配置?
package soundsystem2;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class CDPlayerConfig {// @Bean注解告訴spring這個(gè)方法將會(huì)返回一個(gè)對象,該對象// 要注冊為spring應(yīng)用上下文中的bean.@Beanpublic CompactDisc compactDisc(){return new SgtPeppers();}@Beanpublic CDPlayer cdPlayer(CompactDisc compactDisc){return new CDPlayer(compactDisc);} }通過xml裝配bean
? ?spring剛剛出現(xiàn)時(shí),xml是描述配置的主要方式.但現(xiàn)在xml已經(jīng)不再是Spring的唯一可選方案。spring已經(jīng)有了強(qiáng)大的自動(dòng)化配置和基于java的配置,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:c="http://www.springframework.org/schema/c"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--配置bean --></beans>?
?
?
@Import注解
public class JdbcConfig {@Bean(name="runner")@Scope("prototype")public QueryRunner getRunner(DataSource dataSource){return new QueryRunner(dataSource);}@Bean("dataSource")public DataSource getDataSource(){ComboPooledDataSource dataSource = new ComboPooledDataSource();try {dataSource.setUser("root");dataSource.setPassword("1");dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");dataSource.setDriverClass("com.mysql.jdbc.Driver");}catch (Exception e){e.printStackTrace();}return dataSource;} }?
@PropertySource
?
@ComponentScan(basePackages = {"com.atchina"}) @Import(JdbcConfig.class) @PropertySource("classpath:jdbcConfig.properties") public class SpringConfiguration {}public class JdbcConfig {@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Value("${jdbc.url}")private String url;@Value("${jdbc.driver}")private String driver;@Bean(name="runner")@Scope("prototype")public QueryRunner getRunner(DataSource dataSource){return new QueryRunner(dataSource);}@Bean("dataSource")public DataSource getDataSource(){ComboPooledDataSource dataSource = new ComboPooledDataSource();try {dataSource.setUser(username);dataSource.setPassword(password);dataSource.setJdbcUrl(url);dataSource.setDriverClass(driver);}catch (Exception e){e.printStackTrace();}return dataSource;} }?
總結(jié)
以上是生活随笔為你收集整理的spring三: 装配bean( 在xml中进行显式配置, 在java中进行显式配置)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring二:装配bean(自动装配)
- 下一篇: 前端一HTML:十:选择器