Maven工程搭建,以及基于spring的xml和注解配置

1.首先需要有maven包:

2.本地仓库(有常用的jar包)

3.设置好home、setting和本地仓库地址

4.出现了运行时报错:Error : java 不支持发行版本5

解决方案:这两个设置对应的JAVA编译器选择本地对应版本

5.在setting中设置JAVA版本

简单地写一个关于spring xml配置的小案例:

1.写完之后的目录:

 

2.在pom文件中配置相关jar包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jeferry</groupId>
    <artifactId>day01_springIocXml</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

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

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
</project>

3.配置bean.xml来配置spring将数据注入ioc容器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <!--配置service服务 -->
    <bean id="accountService" class="com.Impl.AccountServiceImpl">
        <!--注入dao层 -->
        <property name="accountDao" ref="accountDao" ></property>
    </bean>
    <!-- 配置dao层-->
    <bean id="accountDao" class="com.Impl.AccountDaoImpl">
        <!--注入QueryRunner -->
        <property name="runner" ref="runner"></property>
    </bean>
    <!-- 配置QueryRunner  scope="prototype" 保证了多线程安全-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!-- 注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mysql"></property>
        <property name="user" value="root"></property>
        <property name="password" value="994129"></property>
    </bean>
</beans>

4.创建Account类对象

package com.domain;

import java.io.Serializable;

/*
账号的实体类接口
 */
public class Account implements Serializable {
    private int id;
    private String name;
    private float 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 float getMoney() {
        return money;
    }

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

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

5.持久层和业务层的实现类:

AccountDaoImpl

package com.Impl;
/*
账户的持久层实现类
 */
import com.Dao.Accountdao;
import com.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

public class AccountDaoImpl implements Accountdao {
    private QueryRunner runner;

    public QueryRunner getRunner() {
        return runner;
    }

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public Account findAccountByid(Integer id) {
        try{
            return runner.query("select * from account where id = ? ", new BeanHandler<Account>(Account.class),id);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?) ",account.getName(),account.getMoney());
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    public void updateAccount(Account account) {
        try{
            runner.update("update account set name = ?,money = ? where id = ? ",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    public void deleteAccount(Integer id) {
        try{
            runner.update("delete from account where id = ? ",id);
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }
}

AccountServiceImpl

package com.Impl;

import com.Dao.Accountdao;
import com.domain.Account;
import com.service.AccountService;

import java.util.List;

/*
业务层的实现类
 */
public class AccountServiceImpl  implements AccountService {
    private Accountdao accountDao;

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

    public List<Account> findAllAccount() {
        
        return accountDao.findAllAccount();
    }

    public Account findAccountByid(Integer id) {
        
        return accountDao.findAccountByid(id);
    }

    public void saveAccount(Account account) {
         
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);

    }

    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);

    }
}

6.测试类编写:

package test;

import com.domain.Account;
import com.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 测试
 */
public class AccountServiceTest {
    @Test
    public void  testFindAll(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //通过getBean方法得到业务层对象
        AccountService as = ac.getBean("accountService",AccountService.class);
        //通过业务层对象调用查询方法进行测试
        List<Account> accounts = as.findAllAccount();
        for(Account account:accounts){
            System.out.println(account);
        }

    }
    @Test
    public void  testFindOne(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //通过getBean方法得到业务层对象
        AccountService as = ac.getBean("accountService",AccountService.class);
        Account one = as.findAccountByid(1);
        System.out.println(one);
    }
    @Test
    public void  testSave(){
        Account account = new Account();
        account.setMoney(2222);
        account.setName("范志强");
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //通过getBean方法得到业务层对象
        AccountService as = ac.getBean("accountService",AccountService.class);
        as.saveAccount(account);
    }
    @Test
    public void  testUpdate(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //通过getBean方法得到业务层对象
        AccountService as = ac.getBean("accountService",AccountService.class);
        Account account = as.findAccountByid(4);
        account.setMoney(23123);
        as.updateAccount(account);
    }
    @Test
    public void  testDelete(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //通过getBean方法得到业务层对象
        AccountService as = ac.getBean("accountService",AccountService.class);
        as.deleteAccount(4);

    }
}

******************************************************************************************************************************

上面的代码在测试类中,每种测试方法前两行都有获取容器,然后通过getBean方法获得业务层对象。代码频繁重复,应该优化,使用注解:

@RunWith(SpringJUnit4ClassRunner.class) 将原来main方法替换成spring 提供的
@ContextConfiguration(classes = SpringConfiguration.class) 告知spring配置的文件,class定位注解配置时java的配置文件,location定位xml配置时xml的所在位置。

还得在实现类对象的初始化定义上面加上@Autowired。

package test;

import com.domain.Account;
import com.service.AccountService;
import config.SpringConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 测试
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    @Autowired
    private AccountService as = null;

    @Test
    public void  testFindAll(){
        //通过业务层对象调用查询方法进行测试
        List<Account> accounts = as.findAllAccount();
        for(Account account:accounts){
            System.out.println(account);
        }

    }
    @Test
    public void  testFindOne(){
        Account one = as.findAccountByid(1);
        System.out.println(one);
    }
    @Test
    public void  testSave(){
        Account account = new Account();
        account.setMoney(2222);
        account.setName("范志强");
        as.saveAccount(account);
    }
    @Test
    public void  testUpdate(){

        Account account = as.findAccountByid(4);
        account.setMoney(23123);
        as.updateAccount(account);
    }
    @Test
    public void  testDelete(){
        as.deleteAccount(4);

    }
}

相应的SpringConfiguration文件:

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * 配置文件,功能类似于bean.xml
 */
//Configuration注解这个类是一个配置属性的类
//ComponentScan注解指定spring
@Configuration
@ComponentScan("com")
public class SpringConfiguration {
    /**
     * 创建一个QueryRunner对象
     *Bean:用于把当前方法的返回值封装成bean对象,注入到spring的ioc容器中
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建一个数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDateSource(){
        try{
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/mysql");
            ds.setUser("root");
            ds.setPassword("994129");
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);

        }

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我可以为您提供一些关于如何使用Maven来构建Spring Boot项目的建议:1.在您的计算机上安装Maven;2.使用Maven来创建Spring Boot项目;3.使用Maven配置Spring Boot项目;4.使用Maven来编译和运行Spring Boot项目。 ### 回答2: Maven是一个Java项目构建工具,可以方便地管理项目依赖、构建和部署等工作。而Spring Boot是一个基于Spring框架的快速开发框架,能够简化Spring应用程序的搭建和部署过程。 下面是使用Maven搭建Spring Boot项目的步骤: 1. 安装Maven:首先需要在本地计算机上安装Maven工具,可以从官方网站下载安装包,并按照指引进行安装。 2. 创建新项目:打开终端或命令提示符,进入要创建项目的目录,然后执行以下命令创建一个新的Maven项目: ``` mvn archetype:generate -DgroupId=com.example -DartifactId=my-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false ``` 上述命令将根据Maven的`maven-archetype-quickstart`模板创建一个新项目。 3. 导入Spring Boot依赖:在项目的`pom.xml`文件中,添加Spring Boot的依赖,可以根据需要添加不同的模块,例如Web模块、数据访问模块等。 4. 编写Spring Boot应用程序:创建一个Java类,作为Spring Boot应用的入口点,使用Spring Boot的注解配置来定义应用程序的行为和特性。 5. 打包项目:执行`mvn clean package`命令,将项目打包成可执行的jar文件。 6. 运行项目:使用`java -jar`命令来启动Spring Boot应用程序,例如`java -jar my-project.jar`。 通过以上步骤,就可以使用Maven快速搭建一个Spring Boot项目了。在项目构建过程中,Maven会自动下载和管理项目所需的依赖,简化了项目配置和管理的工作。同时,Spring Boot框架提供了丰富的功能和约定,使得开发者能够快速地构建出高效、可靠的Java应用程序。 ### 回答3: Maven是一种基于Java的项目管理工具,可以用来管理项目的构建、依赖关系和发布等方面。搭建Spring Boot项目时,可以使用Maven来简化项目的管理和构建过程。 首先,需要在本地安装好Maven,并确保Maven的环境变量配置正确。 接下来,可以使用Maven的命令行工具或者使用集成开发环境(IDE)来创建一个新的Spring Boot项目。在命令行中,可以使用`mvn archetype:generate`命令来生成一个基础的Spring Boot项目。 在生成项目时,可以选择相应的Spring Boot版本、项目的groupId和artifactId等信息。生成项目后,可以使用IDE打开项目,并将其导入为Maven项目。 在项目的pom.xml文件中,可以定义项目的依赖关系和插件配置。通过在dependencies标签中添加需要的依赖,可以引入Spring Boot及其相关的第三方。同时,也可以配置Maven打包时的插件,以及其他项目的构建参数。 在完成依赖关系的配置后,可以使用Maven的命令行工具或IDE提供的Maven插件来构建、运行和发布Spring Boot项目。 通过运行`mvn clean install`命令,可以使用Maven编译项目、运行测试并将可执行的jar包安装到本地的Maven中。 通过运行`mvn spring-boot:run`命令,可以直接在开发环境中运行Spring Boot应用。 通过运行`mvn package`命令,可以将项目打包为可执行的jar包或war包,用于部署到服务器上。 总而言之,使用Maven搭建Spring Boot项目可以简化项目的管理、依赖关系的维护和项目的构建过程。通过合理配置pom.xml文件,可以方便地添加所需的依赖和插件,提高项目的开发效率。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值