栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring中的注解(spring ioc和di)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring中的注解(spring ioc和di)

1.Spring配置数据源 1.1数据源(连接池)的作用

• 数据源(连接池)是提高程序性能如出现的
• 事先实例化数据源,初始化部分连接资源
• 使用连接资源时从数据源中获取
• 使用完毕后将连接资源归还给数据源

常见的数据源(连接池):c3p0,druid

1.2 数据源的开发步骤

① 导入数据源的坐标和数据库驱动坐标
② 创建数据源对象
③ 设置数据源的基本连接数据
④ 使用数据源获取连接资源和归还连接资源

1.3 导入c3p0和druid坐标和mysql驱动坐标
  
    c3p0
    c3p0
    0.9.1.2
  
  
    com.alibaba
    druid
    1.1.12
  

    mysql
    mysql-connector-java
    5.1.32
  
1.4 创建数据源对象,设置数据库基本连接数据,获取资源

1)首先,手动创建c3p0数据源

@Test
    //测试手动创建c3p0数据源
    public void test01() throws Exception {
        //创建c3p0对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        //加载驱动
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        //设置地址
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/db1");
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        //获取资源
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

这里我们使用Test方法来进行测试,因此需要导入Test的坐标依赖

  
    junit
    junit
    4.13
    test
  

运行结果

2)接下来,我们手动创建c3p0数据源,通过加载properties配置文件,方便解耦

创建jdbc.properties配置文件,新建file取名jdbc.properties,然后再文件中添加以下内容

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/db1
jdbc.username = root
jdbc.password = 123456
 @Test
    //测试手动创建c3p0数据源(加载properties配置文件,方便解耦)
    public void test02() throws Exception {
        //读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        String driver = rb.getString("jdbc.driver");
        String url = rb.getString("jdbc.url");
        String username = rb.getString("jdbc.username");
        String password = rb.getString("jdbc.password");


        //创建c3p0对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        //加载驱动
        dataSource.setDriverClass(driver);
        //设置地址
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        //获取资源
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

运行结果

3)最后,我们通过测试spring容器产生数据源对象

创建applicationContext.xml,applicationContext.xml加载jdbc.properties配置文件获得连接信息。
首先,需要引入context命名空间和约束路径:
 命名空间:xmlns:context=“http://www.springframework.org/schema/context”
 约束路径:http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
然后再添加如下代码

    

    
    
        
        
        
        
        

    

测试代码

    @Test
    //测试spring容器产生数据源对象
    public void test03() throws Exception {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource = (DataSource) app.getBean("dataSource");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

运行结果

至此,Spring配置数据源的三种方法已经说明完毕

2.Spring注解开发 2.1 Spring原始注解

注解的作用:主要是代替Bean的配置
1)在dao层新建UserDao接口以及实现类UserDaoImpl

public interface UserDao {
    public void save();
}
public class UserDaoImpl implements UserDao {

    @Override
    public void save() {
        System.out.println("save running");
    }
}

2)在service层新建UserService接口以及实现类UserServiceImpl

public interface UserService {
    public void save();
}

public class UserServiceImpl implements UserService {
    @Override
    public void save() {
        userDao.save();
    }
}

使用注解之前,我们通常会在applicationContext.xml文件中配置Bean对象以及将UserDao对象注入到UserService中,然后在Service层调用Dao层方法。

    

    
        
    

学习了注解后,我们可以使用注解来代替Bean配置
注意:
使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。
例如,我们需要将Dao层的方法注入到service层,因此我们需要扫描Dao和service两个包

    
    

然后,我们只需要在实现类UserDaoImpl和实现类UserServiceImpl中添加注解@Component()

@Component("userDao")
//@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Override
    public void save() {
        System.out.println("save running");
    }
}
@Component("userService")
//@Service("userService")
public class UserServiceImpl implements UserService {

    //
    
    @Resource(name = "userDao")
    private UserDao userDao;
    

    @Override
    public void save() {
        userDao.save();
    }
}

运行结果

说明:
1)使用@Compont或@Repository标识UserDaoImpl需要Spring进行实例化。
2)使用@Compont或@Service标识UserServiceImpl需要Spring进行实例化
3)使用@Autowired或者@Autowired+@Qulifier或者@Resource进行userDao的注入

2.2 Spring新注解

使用上面的注解还是不能完全代替xml文件,因此我们还需要引入一些新的注解。


接下来,我们使用新的注解对上述代码进行改进。
1)引入@Configuration,标志该类为spring的核心配置类
2)引入@ComponentScan({“Dao”,“service”}),该标志是组件扫描的包
3)引入@PropertySource,该标志是引入外部的properties文件
4)引入 @Bean(“dataSource”),spring会将当前方法的返回值以指定名称存储 到spring容器当中,即返回的值的id叫dataSource
5)引入@import,该标志表示可以引入外部的数据源文件

SpringConfiguration文件

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

//标志该类为spring的核心配置类
@Configuration

@ComponentScan({"Dao","service"})//组件扫描的包
//通过 import加载dataSource
@import(DataSourceConfiguration.class)
//如果要加载多个核心配置类,可以使用数组,即大括号括起来
public class SpringConfiguration {

}

DataSourceConfiguration文件

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

// 
@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("dataSource")//spring会将当前方法的返回值以指定名称存储到spring容器当中,即返回的值的id叫dataSource
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        //加载驱动
        dataSource.setDriverClass(driver);
        //设置地址
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

这样,我们就可以摆脱xml配置文件了,但我们测试的时候,加载核心配置文件不能再使用ClassPathXmlApplicationContext来实现ApplicationContext了,需要使用第三种方法:AnnotationConfigApplicationContext

3. Spring整合Junit 3.1 原始Junit测试Spring的问题

在测试类中,每个测试方法都有以下两行代码:

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);

这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

3.2 解决方法

• 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它
• 将需要进行测试Bean直接在测试类中进行注入

3.3 Spring集成Junit的步骤

① 导入spring集成Junit的坐标
② 使用@Runwith注解替换原来的运行期
③ 使用@ContextConfiguration指定配置文件或配置类
④ 使用@Autowired注入需要测试的对象
⑤ 创建测试方法进行测试

3.4 代码实现

① 导入spring集成Junit的坐标


    junit
    junit
    4.13
    test
  

  
    org.springframework
    spring-test
    5.3.16
  

② 使用@Runwith注解替换原来的运行期

@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
}

③ 使用@ContextConfiguration指定配置文件或配置类

@RunWith(SpringJUnit4ClassRunner.class)
//加载spring核心配置文件
//@ContextConfiguration(value = {"classpath:applicationContext.xml"})
//加载spring核心配置类
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
}

④ 使用@Autowired注入需要测试的对象

	@Autowired
    private UserService userService;

    @Autowired
    private DataSource dataSource;

⑤ 创建测试方法进行测试

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {

    @Autowired
    private UserService userService;

    @Autowired
    private DataSource dataSource;

    @Test
    public void test02(){
        userService.save();
        System.out.println(dataSource);
    }
}

运行结果:说明Junit整合成功

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/776587.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号