Spring注解(未完待续2)

若不想使用配置文件xml来配置容器,就引来了新的注解。

@Configuration

作用:

指定当前类是一个配置Spring容器的类。作用和bean.xml是一样的。

细节:

当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。

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

@ComponentScan

作用:

用于通过注解指定spring在创建容器时要扫描的包。

属性:

value:它和basePackages的作用是一样的,都是用于创建容器时要扫描的包。且baskPackages可省略

使用了这个注解等同于在xml中配置这个:

在这里插入图片描述

@Configuration
@ComponentScan(basePackages="com.muzi")
public class SpringConfiguration{
    
}
@Configuration
@ComponentScan("com.muzi")//省略baskPackages
public class SpringConfiguration{
    
}

@bean

当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。查找的方式和Autowired注解的作用是一样的。

作用:

用于把当前方法的返回值作为bean对象存入spring的ioc容器中

属性:

name:用于指定bean的id,当不写时,默认值是当前方法的名称。

@bean("runner")
@scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource){
    return new QueryRunner(dataSource);
}
@bean("dataSource")
public DataSource createDataSource(){
    try{
        comboPooledDataSource ds=new ComboPooedDataSource();
        ds.setDriverClass("com.mysql.djbc.Driver");
        		ds.setJdbcUrl("jdbc:mysql://localhost:3306/muzi");
        ds.setUser("root");
        ds.setPassword("123456");
        return ds;
    }catch(Excption e){
        throw new RuntimeException(e);
    }
}

相当于:

<!--配置QueryRunner-->
<bean id="runner" class="og.apache.commons.dbutls.QueryRunner">
	<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<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/muzi"></property>
    <property name="user" value="root"></property>
    <property name="password" value="123456"></property>
</bean>

@import

作用:

用于在主配置类中导入其他的子配置类,而不需要特意在主配置类的ComponentScan注解中在加入子配置类全类名

需传入子配置类的字节码

@ComponentScan("com.muzi")
@import(JdbcConfig.class)
public class SpringConfiguration{
    
}

Spring整合Junit的注解配置

先导Jar包

【注意】当我们使用Spring 5.x版本的时候,要求junit的java必须是4.12及以上。

@RunWith

把原有的main方法替换掉

@ContextConfiguration

作用:

告诉spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置

属性:

Location : 指定xml文件的位置,加上classpath关键字,表示在类路径下

classes : 指定注解类所在地位置。

@RunWith(SpringJUnit4ClassRunner.class@ContextConfiguration(classes=SpringConfguration.class)
public class AccountServiceTest{
    
}
发布了38 篇原创文章 · 获赞 38 · 访问量 2736

猜你喜欢

转载自blog.csdn.net/l13kddd/article/details/105208867