spring ioc 的常用给配置和注解

数据库配置文件


## db.properties
## 加上jdbc.前缀原因是 怕回头你还有些业务 需要使用 重名的属性名!!!
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=root

redis配置文件

redis.host=localhost
redis.port=6379
#最大空闲连接数
redis.maxIdle=30
redis.maxTotal=50
redis.minIdle=10
redis.maxWaitMillis=2000

pom.xml


  <dependencies>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <!-- 接触到的数据库连接池 c3p0 基本没人用了 性能比较差-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.5</version>
    </dependency>

    <!--阿里的 druid连接池 号称性能非常高-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.18</version>
    </dependency>

    <!--号称世界第一 hikari 光之子 -->
    <dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>HikariCP</artifactId>
      <version>3.4.2</version>
    </dependency>


    <!--mysql的驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>

    <!--导入spring 关于测试用例jar包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <!--有个要求 junit测试要版本号4.12 之上-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>3.1.0</version>
    </dependency>
  </dependencies>

beans.xml

    <!--导入外部属性文件 classpath 类路径下哪里-->
    <!--命名空间使用 可以由提示的!!!!-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>


    <!--如果一个类 不是咱们写 您就是老老实实配置 -->
    <!--注入 老牌的c3po-->
    <bean id="datasource01" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>


    <!--druid连接池-->
    <bean id="datasource02" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>

    </bean>

    <!--hikari数据库连接池  后面就是springboot框架 默认数据库连接池-->
    <bean id="datasource03" class="com.zaxxer.hikari.HikariDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--
        非常关键的一步  告诉spring框架 扫描哪些包下 有可能存在 我们需要组件对象
        component-scan:组件扫描的意思
        如果存在多个包 中间以逗号分隔

        可以扫描父包 但是不建议  原因:所谓扫描 底层就是挨个遍历文件夹 查看那个类 都扫描性能会差!!
        建议你精确到您需要的包名
    -->
    <context:component-scan base-package="com.dao,com.service"></context:component-scan>


//用在dao的实现类上
@Component
@Repository
public class ProductDaoImpl  implements ProductDao{
	//注入属性  不用写set.. 方法
 	 @Autowired
    private DataSource dataSource;
    .....
}



//用在service的实现类上
@Component
//"别名"     一般不起别名,使用默认
@Service("abc")
public class ProductServiceImpl implements ProductService{.....}

//在测试类中直接调用
 context.getBean(ProductService.class);
 

使用配置类

DatasourceConfig.java

/**
 * <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
 * 跟它是一个作用
 */
@PropertySource("classpath:db.properties")
public class DatasourceConfig {

    /**
     * 就是读取properties里面值 赋值给属性!!!
     */
    @Value("${jdbc.driver}")
    private String driverClassname;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;




    //如果有一些 不是我们写的类  我们可以使用方法来做

    /**
     * 方法名随便起 最好见名知意
     * 方法的返回值 是你希望放入容器对象
     *
     * 方法上必须加上注解 @Bean
     *
     */
    @Bean
    public DataSource generateDatasource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassname);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }
}

Redis.java

@PropertySource("classpath:redis.properties")
public class RedisConfig {
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private int port;


    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.maxTotal}")
    private int maxTotal;
    @Value("${redis.minIdle}")
    private int minIdle;
    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;
    @Bean
    public GenericObjectPoolConfig createRedisConfig(){
        GenericObjectPoolConfig config=new JedisPoolConfig();

        config.setMaxIdle(maxIdle);
        config.setMaxTotal(maxTotal);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        return config;
    }

    /**
     * 如果你需要用另外一个在容器放着的对象 只要把写到参数就可以了
     *
     */
    @Bean
    public JedisPool createJedisPool(GenericObjectPoolConfig config){


        //创建这个jedis连接池代码
        JedisPool pool = new JedisPool(config,host,port);

        return pool;

    }



}

springconfig.java

/**
 *  这个类 就要替代咱们那个xml了
 *  @Configuration 表示这个类是spring的配置文件类
 *
 *
 */
@Configuration
/**
 * <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
 * 跟它是一个作用
 */
//@PropertySource("classpath:db.properties")
/**
 * <context:component-scan base-package="com.itheima.dao,com.itheima.service,com.itheima.xyz"></context:component-scan>
 * 跟它一个作用
 */
@ComponentScan({"com.itheima.dao","com.itheima.service","com.itheima.xyz"})
/**
 * 把拆出去的配置类 到如核心配置类中
 */
@Import({DatasourceConfig.class,RedisConfig.class})
public class SpringConfig {


}

测试的方法

方法一

public class ProductTest {
    /**
     * 测试一下获取productService对象
     */
    @Test
    public void test01() {
        //创建一个spring的容器对象

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        ProductService productService = context.getBean(ProductService.class);
        System.out.println("测试获取ProductService:"+productService);
    }
}

方法二

/**
 * 运行环境交给了 spring控制
 */
@RunWith(SpringJUnit4ClassRunner.class)
/**
 * 告诉spring配置类是哪个类!!!
 */
@ContextConfiguration(classes = SpringConfig.class)
public class UserTest {

    @Autowired
    private UserService userService;



    /**
     * 测试是逻辑操作 登录操作
     */
    @Test
    public void test03(){
        //UserService userService = context.getBean(UserService.class);

        userService.login("zhangsan","123");

    }

    /**
     * 测试 保存操作
     */
    @Test
    public void test04(){
        //UserService userService = context.getBean(UserService.class);

        userService.save(new User());

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

娃娃 哈哈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值