首先创建一个配置类,他的作用代替了xml配置文件。
用@Configuration注解来指定当前类是个配置类
用@ComponentScan指定spring在创建容器时要扫描的包 他的属性有basePackages
@Configuration
@ComponentScan(basePackages="com.qst.service")
public class configuration(){
}
此配置方法带替了xml中的
<context:Component-Scan base-package="com.qst.service> </context:Component-Scan>
@Bean注解的作用就是将当前方法的返回值作为bean对象存入ioc容器中
@Configuration
@ComponentScan(basePackages="com.qst.service")
public class configuration(){
@Bean(name="dateSouce")
public DateSouce createDate( ){
try{
ComPooledDateSouce = new ComPolledDateSouce();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring");
ds.setUser("root");
ds.setPassWord("root");
return ds;
}catch (Expection e){
throw new RuntimeExpection (e);
}
}
bean注解进一步替代了以下xml
<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/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
此时在我们的main函数中依旧调用的是XML文件,所以想要脱离应将
ClassPathXmlApplicationContext(bean.xml) 改为 AnnotationConfigApplicationContext(configuration.class)
ApplicationContext ac= new AnnotationConfigApplicationContext(configuration.class);
@import注解用于导入其他配置类,有import注解的为父配置类用来导入其他子配置类
@PrepertySource注解 用于指定properties配置文件 ,从而避免连接数据库时 文件写死