Spring利用java配置方式进行快速搭建

Spring使用java方式配置实现

背景

Spring的配置方式有三种:
1.最古老的xml配置方式
2.jdk1.5之后的注解方式进行配置
3.spring4.x推荐使用的java配置方式

描述


简化配置文件


注解说明
//常用的注解说明
@Configuration
    //作用于类上,表示的是该类是一个配置文件,相当于配置文件xml

@ComponentScan(basePackages = "com.pkk.springboot")
    //作用于类上,配置扫描的包

@PropertySource(value = "classpath:db.properties", ignoreResourceNotFound = true)
    /*作用于类上,加载配置文件,(如数据库配置文件db.properties)加载多个时@PropertySource(value ="classpath:db.properties","classpath:db1.properties",...),后面的属性为属性不存时进行忽略在忽略(ignoreResourceNotFound = true)*/

@Value(value = "${db_username}")
    //再用于成员变量上,用于获取配置文件的属性

@Bean
    //可以作用于方法上,相当于注入获取对象,相当于配置文件xml中的bean对象

代码示例

1.//配置文件(java)

//配置文件(java)
package com.pkk.springboot.utils.springconfig;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.jolbox.bonecp.BoneCPDataSource;
import com.pkk.springboot.dao.UserDAO;

/**
 * @author peikunkun
 * @version V1.0
 * @Title: SpringBoot
 * @Package com.pkk.springboot.utils.springconfig
 * @Description: <>
 * @date 11/13 0013 16:09
 */
@Configuration//表示是一个配置的xml,也就是标识为xml的配置文件
@ComponentScan(basePackages = "com.pkk.springboot")//配置扫描的包
@PropertySource(value = "classpath:db.properties", ignoreResourceNotFound = true)/*配置多个时@PropertySource(value = "classpath:db.properties","classpath:db1.properties"),后属性为属性不存在忽略*/
public class SpringConfig {


    @Value(value = "${db_username}")
    private String username;
    @Value(value = "${db_password}")
    private String password;
    @Value(value = "${db_url}")
    private String url;
    @Value(value = "${db_driver}")
    private String driver;


    @Bean//相当于配置文件xml中的bean对象
    public UserDAO getUserDAO() {
        return new UserDAO();
    }


    /*配置成xml中的bean[数据源]*/
    @Bean
    public BoneCPDataSource boneCPDataSouce() {
        BoneCPDataSource boneCPDataSource = new BoneCPDataSource();
        boneCPDataSource.setDriverClass(driver);
        boneCPDataSource.setJdbcUrl(url);
        boneCPDataSource.setUsername(username);
        boneCPDataSource.setPassword(password);
        boneCPDataSource.setIdleMaxAge(30);
        /*检查未使用连接池的最大存活时间,默认是60,单位是分,永远存活设置成0*/
        boneCPDataSource.setIdleMaxAgeInMinutes(30);
        /*单位是分,默认240,取消设置0,检查数据库连接池的空间的连接的间隔时间*/
        boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60);
        return boneCPDataSource;
    }


}

2.db.properties

db_driver=com.mysql.jdbc.driver
db_username=***
db_password=***
db_url=jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true

3.Service类

package com.pkk.springboot.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pkk.springboot.dao.UserDAO;
import com.pkk.springboot.model.UserInfo;

/**
 * @author peikunkun
 * @version V1.0
 * @Title: SpringBoot
 * @Package com.pkk.springboot.base
 * @Description: <>
 * @date 11/13 0013 15:47
 */
@Service
public class UserService {

    // 注入Spring容器中的bean对象
    @Resource
    private UserDAO userDAO;

    public List<UserInfo> queryUserList() {
        // 调用userDAO中的方法进行查询
        return this.userDAO.queryUserList();
    }
}

4.dao层(未使用@Repository注解进行注入(模拟数据库))

package com.pkk.springboot.dao;

import java.util.ArrayList;
import java.util.List;

import com.pkk.springboot.model.UserInfo;

/**
 * @author peikunkun
 * @version V1.0
 * @Title: SpringBoot
 * @Package com.pkk.springboot.dao
 * @Description: <>
 * @date 11/13 0013 15:47
 */
public class UserDAO {

    public List<UserInfo> queryUserList() {

        ArrayList<UserInfo> users = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            UserInfo user = new UserInfo();
            user.setUsernam("username_" + i);
            user.setUserpwd("password_" + i);
            user.setId(i);
            users.add(user);
        }
        return users;
    }


}

5.测试类

package com.pkk.springboot.test;

import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.pkk.springboot.model.UserInfo;
import com.pkk.springboot.service.UserService;
import com.pkk.springboot.utils.springconfig.SpringConfig;

/**
 * @author peikunkun
 * @version V1.0
 * @Title: SpringBoot
 * @Package com.pkk.springboot.test
 * @Description: <>
 * @date 11/13 0013 16:07
 */
public class Test1 {

    public static void main(String[] args) {
        // 通过Java配置来实例化Spring容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

        // 在Spring容器中获取Bean对象
        UserService userService = context.getBean(UserService.class);

        // 调用对象中的方法
        List<UserInfo> list = userService.queryUserList();
        for (UserInfo user : list) {
            System.out.println(user.getUsernam() + ", " + user.getUserpwd() + ", " + user.getId());
        }

        // 销毁该容器
        context.destroy();
    }
}

4.代码说明

1.没有使用spring配置文件,主要是以类进行代替
2.其他均采用注解的形式进行注入(@Service,@Repository3.这里只是简单介绍一下,Spring使用java配置方式的使用
4.此验证了使用java配置方式的注入是成功的(主要看dao层)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值