spring 之ioc注解,案例,整合单元测试(02)

来源:互联网 发布:网络成瘾调查问卷 编辑:程序博客网 时间:2024/05/22 05:30

(★)ioc注解方式

步骤:

导入jar包:

核心4个+2个日志+aop
jar包
在类上添加注解
  作用:让资源让spring来管理,相当于在xml配置一个bean

@Component(value="名字") //<bean id="" class="">

在基本和String类型属性上注入

@Value("值")

开启组件扫描(扫描spring下的这些注解)

xml方式:applicationContext.xml

导入约束:beans和context约束在配置文件中

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context"     xsi:schemaLocation="http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans.xsd            http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context.xsd">

类上注解

  @Component(value=”“):声明这个对象加入spring管理 名称为value的值(开发中我们使用这个注解比较少)

三个衍生注解

  @Controller(value=”“):加在web层类上的
  @Service(value=”“):加在service层类上的
  @Repository(value=”“):加在dao层类上的

  @Scope(value=”“) //声明bean的作用返回
常用值:
  singleton|prototype 单例|多例

属性上注解(使用注解,属性可以没有set方法,注解可以加在属性上)

基本类型和String类型
  @Value(value=”“)

bean类型
  @Autowired :默认按照类型自动装配.
这里开发的时候会有个坑 :
  若spring容器中有同一个类型的两个对象的时候,会把属性名字作为bean的id去容器中查询

   若能找到,就注入
   若找不到,抛异常
配置@Qulifier(value=”bean的名称”)使用名称注入.

扩展:jdk的注解

  @Resource(name=”“) :有name属性的时候使用名称注入,没有name属性的时候变成类型注入

方法上注解(了解)

  @PostConstruct:相当于 init-method 在spring创建bean的时候要调用的方法
  @PreDestroy:相当于 destroy-method 在spring销毁bean的时候要调用的方法

下面有个小例子:

//@Component("customerService")//普通方式 开发一般用@Service("customerService")//@Repository("customerService")//不建议@Scope(value="prototype")//设置成为多例public class CustomerServiceImpl implements CustomerService {    //下面有两张种配置方式都可以    //用spring的方式配置    /*@Autowired //默认按照类型自动装配    @Qualifier("customerDao") //配置@Autowired使用 就是名称注入    private CustomerDao customerDao;*/    //jdk的注解配置    //@Resource(name="customerDao")//有name属性使用名称注入    @Resource//没有name属性使用类型注入    private CustomerDao customerDao;    @Override    public void save() {        System.out.println("service中的save方法执行了");        customerDao.save();    }}

Spring中 xml和注解对比

  xml和注解:xml维护起来方便而注解开发起来较为方便

注意:

  xml方式使用于所有场景
  注解只能使用于自己编写的类

开发中使用那种方式:

  1.纯xml的方式
  2.★xml和注解混合的方式 一般使用xml管理bean 使用注解注入属性

ioc的纯注解方式:(理解)

  刚才看到我们保留一个xml文件,他的主要作用就是 开启组件扫描
我们如果可以将组件扫描通过注解配置的话,这个xml文件就可以删除了

这时候我们需要编写一个类. 例如:SpringConfig
在类上添加一个注解:
  @ComponentScan(value=”包名”)

创建工厂类的时候
new AnnotationConfigApplicationContext(Class 配置类的字节码对象)
例如:

ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

我们还可以在配置类上添加一个注解(现在没有问题,但是整合ssh框架时的时候需要加)

@Configuration//声明他是一个配置类

下面是案例的代码:
配置类的代码:

@ComponentScan(value="com.xx")//相当于<context:component-scan base-package="com.xx"/>@Configuration//声明他是一个配置类public class SpringConfig {}

bean类的代码

@Component("userDao")public class UserDaoImpl implements UserDao {    @Value("华为")    private String name;    @Override    public void save() {        System.out.println("userdao执行了保存方法,保存了"+name);    }    public void setName(String name) {        this.name = name;    }}

(理解)其他的注解

案例需求:

  通过连接池(DataSource)获取一个连接
连接池规范:
  所有的连接池都实现了 javax.sql.DataSource接口
  获取连接的时候: getConnection()
  释放资源:直接调用连接的close方法就可以归还到连接池
  使用c3p0获取一个连接

步骤:

1.导入jar包(spring依赖包)
2.创建连接池 new ComboPooledDataSource()
3.提供一个配置文件

  一个项目中需要一个连接池,我们可以将连接池交给spring管理,
通过工厂类获取连接池,从而调用getConnection就可以获取一个连接了.

下面我用两种方式完成把连接池交给spring管理

1.xml方式

现在src文件下设置一个jdbc. properties
先看配置文件:applicationContext.xml:

<!-- 先加载属性文件 -->     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="location" value="classpath:jdbc.properties"/>     </bean><!-- 再配置连接池 -->     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="${jdbc.driverClass}"/>        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>        <property name="user" value="${jdbc.user}"/>        <property name="password" value="${jdbc.password}"/>     </bean>     

配置一个jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver     jdbc.jdbcUrl=jdbc:mysql:///hibernate02_62  jdbc.user=root jdbc.password=root

下面编写测试类:

public class TestConnXml {    public static void main(String[] args) throws SQLException {        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//加载配置文件        DataSource ds = (DataSource) context.getBean("dataSource");        System.out.println(ds.getConnection());    }

2.注解方式

就编写两个类:
第一个类SpringConfig

@Configuration//声明是配置文件@PropertySource("classpath:jdbc.properties")//执行属性文件的位置@Import({JdbcConfig.class})//导入其他的配置类public class SpringConfig {    @Bean//专门用来加载解析属性配置文件 spring4.3版本以上就不需要这样个了    public static PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){        return new PropertySourcesPlaceholderConfigurer();    }}

再编写一个JdbcConfig

@Configurationpublic class JdbcConfig {        //属性注入        @Value("${jdbc.driverClass}")        private String driverClass;        @Value("${jdbc.jdbcUrl}")        private String jdbcUrl;        @Value("${jdbc.user}")        private String user;        @Value("${jdbc.password}")        private String password;        //创建一个连接池对象放入spring管理        @Bean(name="dataSource") //将方法的返回值 起个名字 放入spring容器中        public DataSource createDataSource(){            //创建连接池            ComboPooledDataSource ds = new ComboPooledDataSource();            try {                ds.setDriverClass(driverClass);                ds.setJdbcUrl(jdbcUrl);                ds.setUser(user);                ds.setPassword(password);            } catch (Exception e) {                e.printStackTrace();            }            return ds;        }}

测试类和jdbc.properties与xml方式相同,这样就实现了将连接池交给spring管理

其他注解小结

配置类上的注解

@Configuration//声明他是一个配置类
@PropertySource(value=”classpath:jdbc.properties”)//加载指定位置的配置文件
@Import(value={JdbcConfig.class})//导入其他的配置类
@ComponentScan(value=”com.xx”)//开启组件扫描

方法上的注解:

@Bean(name=”dataSource”)//将方法的返回值 起个名字 加入spring管理中.也可以没name属性.

(★)Spring整合单元测试

这个也有两种方式,xml和纯注解方式,xml的形式开发中用的比较多.

xml方式(★)

步骤:
  导入jar包:核心 test
jar包
  在测试环境上有junit环境
  在测试类上添加注解

@RunWith(SpringJunit4ClassRunner.class) //修改测试用的方式,使用spring测试(好处:使用spring的工厂)

指定spring配置文件路径和名称

@ContextConfiguration("classpath:applicationContext.xml") 

xml里只要把bean交给spring管理就行

<bean id="orderDao" class="com.xx.OrderDao"></bean>

在测试类中就可以使用spring注入
  需要用那个属性 就在属性上添加@Autowired或者@Resource

例如:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class TestSpringTest {    @Autowired    private OrderDao orderDao;    @Test    public void save(){        orderDao.save();    }    @Test    public void delete(){        orderDao.delete();    }}

纯注解方式(了解即可)

步骤:
  导入jar包:核心 test,同上
  在测试环境上有junit环境
  在测试类上添加注解

@RunWith(SpringJunit4ClassRunner.class) //修改测试用的方式,使用spring测试(好处:使用spring的工厂)

指定spring配置文件路径和名称 @ContextConfiguration(配置类)
在测试类中就可以使用spring注入
需要用那个属性 就在属性上添加@Autowired或者@Resource

代码如下:
配置类只需要开启组件扫描和声明是配置文件即可

@ComponentScan(value="com.xx")@Configurationpublic class SpringConfig {}

测试类也只是引入xml变成引入.class配置文件的编化:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes={SpringConfig.class})public class TestSpringTest {    @Autowired    private OrderDao orderDao;    @Test    public void save(){        orderDao.save();    }    @Test    public void delete(){        orderDao.delete();    }}
阅读全文
0 0
原创粉丝点击