关于spring的xml和注解配置的区别

24 篇文章 0 订阅

文章目录

注解配置

在这里插入图片描述

  • 在某个具体的Java类第一种直接bean
package com.lanou3g.dao;

import com.lanou3g.bean.Book;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component  // 用这个注解标注的类会自动被ioc容器管理,成为一个bean
public class BookDaoImpl {

    @Autowired  // 按照类型来自动注入属性
    @Qualifier("dataSource")    //强制按照名称自动注入属性值
    private DataSource dataSource;

    public List<Book> queryAllBook() {
        QueryRunner runner = new QueryRunner(dataSource);
        String sql = "select * from book;";
        ResultSetHandler<List<Book>> rsh = new BeanListHandler(Book.class);
        List<Book> bookList = new ArrayList<>();
        try {
            bookList = runner.query(sql, rsh);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return bookList;
    }

}

  • 第二种设置beans 还有bean
package com;

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

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

@Configuration  //相当于用注解配置了一个xml配置文件(相当于xml中的<beans>)
//引入了一个外部的properties文件(相当于xml中的
//<context:property-placeholder location="classpath:jdbc.properties" />)
@PropertySource("classpath:jdbc.properties")
public class MyDataSource {

    //@Value用于取引入进来的properties文件中key对应的值
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.user}")
    private String user;
    @Value("${jdbc.password}")
    private String password;
    @Value("${c3p0.maxPoolSize}")
    private int maxPoolSize;
    @Value("${c3p0.minPoolSize}")
    private int minPoolSize;
    @Value("${c3p0.maxIdleTime}")
    private int maxIdleTime;


    @Bean   //配置了一个bean(相当于在xml中写了一个<bean>)
    public DataSource dataSource() {
        ComboPooledDataSource dataSource =  new ComboPooledDataSource();
        dataSource.setJdbcUrl(url);
        try {
            dataSource.setDriverClass(driver);
        } catch (PropertyVetoException e) {
        }
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setMaxPoolSize(maxPoolSize);
        dataSource.setMinPoolSize(minPoolSize);
        dataSource.setMaxIdleTime(maxIdleTime);
        return  dataSource;
    }
}

  • 在main方法调用
package com.lanou3g;

import com.MyDataSource;
import com.lanou3g.dao.BookDaoImpl;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.sql.DataSource;

/**
 * 程序入口
 * 该工程演示了用纯注解的配置方式使用Spring
 */

@Configuration //相当于用注解配置了一个xml配置文件(相当于xml中的<beans>)
// 如果说其他的注解配置bean不在扫描包路径下,就需要通过@Import注解显式导入
// 如果咱们把MyDataSource类放到扫描包路径下(比如com.lanou3g下)就不需要@Import导入了
@Import(MyDataSource.class)
//这里面之所以要导入,是因为MyDataSource.class不再com.lanou3g下面,扫描不到
@ComponentScan(basePackages = "com.lanou3g")
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(App.class);
        ctx.registerShutdownHook();

        BookDaoImpl bookDao = ctx.getBean(BookDaoImpl.class);
        System.out.println(bookDao.queryAllBook());

    }
}
/**
 * 整个App类就相当于xml中的
 *  <beans>
 *      <import reources="xxxx.xml" />
 *      <context:component-scan base-package="com.lanou3g" />
 *  </beans>
 *
 */

xml配置

  • 在resource中建application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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
       ">

    <!-- 引入外部的properties -->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 引用外部的properties中的属性 -->
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="user" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
        <property name="minPoolSize" value="${c3p0.minPoolSize}" />
        <property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
    </bean>

    <!-- 配置dao,注入数据源 -->
    <bean id="bookDao" class="com.lanou3g.dao.BookDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置dao,注入数据源 -->
    <bean id="bookTypeDao" class="com.lanou3g.dao.BookTypeDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>
  • 在测试类中运行
package com.lanou3g;

import com.lanou3g.bean.Book;
import com.lanou3g.dao.BookDaoImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 程序入口
 *
 * 该工程演示了用纯xml的配置方式使用Spring
 *
 */
public class App {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        BookDaoImpl bookDao = ctx.getBean(BookDaoImpl.class);
        List<Book> bookList = bookDao.queryAllBook();
        System.out.println(bookList);
        // 优雅的关闭IOC容器
        ctx.registerShutdownHook();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值