Spring完全使用注解(没有xml)实现IoC

一、回顾之前的bean.xml

	<context:component-scan base-package="com.uos"></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.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/account?serverTimezone=UTC"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

二、使用注解方式实现bean.xml

1、@Configuration注解

作用:指定当前类是一个配置类.
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。

//@Configuration
public class SpringConfiguration {
}
 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);

2、@ComponentScan注解

作用:用于通过注解指定Spring在创建容器时要扫描的包。
属性:value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。我们使用此注解就等同于在xml中配置了:
<context:component-scan base-package="com.uos"></context:component-scan>

//@Configuration
@ComponentScan(basePackages = {"com.uos"})
public class SpringConfiguration {
}

3、@Bean注解

作用:用于把当前方法的返回值作为bean对象存入Spring的IoC容器中。
属性: name:用于指定bean的id。当不写时,默认值是当前方法的名称
细节:当我们使用注解配置方法时,如果方法有参数,Spring框架会去容器中查找有没有可用的bean对象。
查找的方式和Autowired注解的作用是一样的。

	@Bean(name = "runner")
    public QueryRunner createQueryRunner(DataSource ds) {
        return new QueryRunner(ds);
    }
    @Bean(name = "datasource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

4、@Import注解

作用:用于导入其他的配置类。
属性: value:用于指定其他配置类的字节码。
当我们使用@Importt的注解之后,有@Import注解的类就父配置类,而导入的都是子配置类。

//@Configuration
@ComponentScan(basePackages = {"com.uos"})
@Import(JdbcConfiguration.class)
public class SpringConfiguration {

}

5、@PropertySource注解

作用:用于指定properties文件的位置。
属性:value:指定文件的名称和路径。
关键字:classpath,表示类路径下

//@Configuration
@ComponentScan(basePackages = {"com.uos"})
@Import(JdbcConfiguration.class)
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {

}
原创文章 154 获赞 48 访问量 8539

猜你喜欢

转载自blog.csdn.net/weixin_41842236/article/details/105924387