Spring 新注解

 

 @Configuration
 @ComponentScan
 @Import

@Configuration
@ComponentScan("com.yangjiang")
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}

@PropertySource

@value

@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
@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

@Bean(name="dataSource")
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}

测试加载核心配置类创建Spring容器

@Test
public void testAnnoConfiguration() throws Exception {
ApplicationContext applicationContext = new 
AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = (UserService) 
applicationContext.getBean("userService");
userService.save();
DataSource dataSource = (DataSource) 
applicationContext.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}

 

posted on 2021-11-07 15:38  季昂  阅读(42)  评论(0)    收藏  举报