Spring框架核心IOC的使用:配置式开发+注解式开发+纯注解式开发

Spring框架IOC合集:
Spring框架核心IOC的使用:IOC的作用+Bean管理+实例化Bean的方式+DI依赖注入
Spring框架核心IOC的使用:配置式开发+注解式开发+纯注解式开发

一、准备工作

1.1 配置maven

新建maven项目(maven的下载安装及配置
pom文件中加入坐标依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.12</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<!-- 连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>
<!-- mysql驱动包-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

1.2 创建数据库

create database spring_db;
use spring_db;
create table account(
id int primary key auto_increment,
name varchar(40),
money double
)character set utf8 collate utf8_general_ci;
INSERT INTO `account` VALUES ('1', '老王', '1000');
INSERT INTO `account` VALUES ('2', '小王', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');

在这里插入图片描述

在entity包下新建Account类,与数据库中的account相对应

public class Account {
    private int id;
    private String name;
    private Double money;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

二、IOC配置文件开发的示例

2.1 配置dao层

在dao层下新建接口AccountDao,新建包impl,在impl下新建类AccountDaoImpl,重写findAll方法

public interface AccountDao {
    //查询所有账号
    public List<Account> findAll() ;
}

在连接池这一部分,用set方法注入的方式,注入druidDataSource,也就是给它赋值

public class AccountDaoImpl implements AccountDao {
    private DruidDataSource druidDataSource;

    public void setDruidDataSource(DruidDataSource druidDataSource) {
        this.druidDataSource = druidDataSource;
    }

    @Override
    public List<Account> findAll(){
        //创建连接池
//        DruidDataSource druidDataSource = new DruidDataSource();
//        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
//        druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring_db");
//        druidDataSource.setUsername("root");
//        druidDataSource.setPassword("2020");

        //创建数据库对象
        Connection connection=null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Account> list = new ArrayList<Account>();
        //获取连接
        try {
            connection = druidDataSource.getConnection();


            //编写sql
            String sql = "select * from account";
            //预编译
            statement = connection.prepareStatement(sql);
            //执行sql语句
            resultSet = statement.executeQuery();
            //遍历结果集
            while (resultSet.next()){
                Account account = new Account();
                account.setId(resultSet.getInt("id"));
                account.setName(resultSet.getString("name"));
                account.setMoney(resultSet.getDouble("money"));
                list.add(account);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        return list;
    }
}

2.2 配置service层

接下来在service层下新建接口AccountService,新建impl包,包下新建AccountServiceImpl类

public interface AccountService {
    //查询所有账号
    public List<Account> findAll() ;
}

重写的findAll调用dao层的findAll方法,在这里注入accountDao

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAll() {

        return accountDao.findAll();
    }
}

完成dao层service层还有entity层之后的目录层级

在这里插入图片描述

2.3 配置applicationContext2.xml

接下来是配置文件

<!--    连接池对象-->
    <bean id="dr" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_db"></property>
        <property name="username" value="root"></property>
        <property name="password" value="2020"></property>
    </bean>
<!--    service层-->
    <bean id="asi" class="com.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="adi"></property>
    </bean>
<!--    dao层-->
    <bean id="adi" class="com.dao.impl.AccountDaoImpl">
        <property name="druidDataSource" ref="dr"></property>
     </bean>

2.4 测试

创建测试类AccountServiceTest

在这里插入图片描述

public class AccountServiceTest {
    @Test
    public void run(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext2.xml");
        AccountService as = (AccountService) ac.getBean("asi");
        List<Account> all = as.findAll();

        for (Account account:all){
            System.out.println(account);
        }

    }
}

运行结果
在这里插入图片描述

三、IOC注解式开发

3.1 开启注解扫描

在配置文件中加入

<context:component-scan base-package="com"></context:component-scan>

在加载配置文件时会扫描com包中的类,有哪些交给ioc管理

3.2 bean管理类常用的注解

bean管理类常用的4个注解(作用相同,推荐使用在不同分层上)

  1. @Component 普通的类
  2. @Controller 表现层的类
  3. @Service 业务层的类
  4. @Repository 持久层的类

3.3 依赖注入相关的注解

  1. @Value 用于注入简单类型(基本类型+字符串)

  2. @Autowired 默认按类型进行自动装配(自定义引用类型)

  3. @Qualifier 不能单独使用,必须要和@Autowired一起使用,使用value参数指定名称,强制使用名称注入

  4. @Resource java提供的注解,也可以达到强制使用名称注入的作用,这个注解可以单独使用,但是注意使用name参数指定名称

3.4 对象生命周期注解

@Scope 取值singleton(单例)prototype(多例)

3.5 初始化方法和销毁方法注解

  1. @PostConstruct 相当于init-method 该注解作用到方法上
  2. @PreDestroy 相当于destroy-method 该注解作用到方法上

3.6 示例

新建Person类
加入注解@Component,此类交给ioc管理,不加参数默认的标识是person
@Value(“LiMing”)给变量name注入值

@Component
public class Person {
    @Value("LiMing")
    private String name;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

新建类Car,在这个类中给Person类型的变量注入值@Autowired,按照类型注入,如果要按照名称注入,需加入注解@Qualifier(“person”)

@Component
public class Car {
    @Value("xiaomiSU7")
    private String name;

    @Autowired
    private Person person;

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", person=" + person +
                '}';
    }
}

在配置文件中开启注解扫描

<context:component-scan base-package="com"></context:component-scan>

编写测试类,然后运行

    @Test
    public void run(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext2.xml");
        Car car = (Car) ac.getBean("car");
        System.out.println(car);
    }

在这里插入图片描述

四、IOC纯注解式开发

IOC纯注解开发使用配置类代替配置文件中的注解扫描

  • @Configuration声明当前类是配置类
  • @ComponentScan(“com”)扫描指定的包
  • @Import(SpringConfig2.class)导入其他的配置类
  • @Bean只能写到方法上,表明使用此方法创建一个对象,并把创建好的对象保存到ioc容器中,可以帮助我们配置第三方的类
  • 创建工厂,加载配置类:
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);

4.1 新建配置类

新建util包,包里面新建配置类

在这里插入图片描述

//声明当前类是配置类
@Configuration
//扫描指定的包
@ComponentScan("com")
//导入其他的配置类
@Import(SpringConfig2.class)
public class SpringConfig {
    //@Bean只能写到方法上,表明使用此方法创建一个对象,并把创建好的对象保存到ioc容器中
    @Bean
    public DruidDataSource createDataSource(){

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring_db");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("2020");

        return druidDataSource;
    }
}
public class SpringConfig2 {
}

主配置类有注解@Configuration,导入的配置类可以没有@Configuration

4.2 配置service层和dao层

修改AccountDaoImpl类,使用注解注入,并且将类交给ioc管理

@Repository
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private DruidDataSource druidDataSource;


    @Override
    public List<Account> findAll(){
        //创建连接池

        //创建数据库对象
        Connection connection=null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Account> list = new ArrayList<Account>();
        //获取连接
        try {
            connection = druidDataSource.getConnection();


            //编写sql
            String sql = "select * from account";
            //预编译
            statement = connection.prepareStatement(sql);
            //执行sql语句
            resultSet = statement.executeQuery();
            //遍历结果集
            while (resultSet.next()){
                Account account = new Account();
                account.setId(resultSet.getInt("id"));
                account.setName(resultSet.getString("name"));
                account.setMoney(resultSet.getDouble("money"));
                list.add(account);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        return list;
    }
}

修改AccountServiceImpl

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAll() {

        return accountDao.findAll();
    }
}

4.3 测试

修改测试类中的run方法

@Test
public void run(){


    //创建工厂,加载配置类
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    AccountService accountService = (AccountService) ac.getBean("accountServiceImpl");
    System.out.println(accountService.findAll());

}

运行结果

在这里插入图片描述

  • 26
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值