基本Spring注解方式搭建架构查询数据

本文详细介绍了Spring框架中的各种注解如@Component,@Configuration,@Autowired等的使用,以及如何在Java项目中建立数据库连接,配置JdbcTemplate,实现三层架构(DAO,Service,Controller)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.注解

(1)传统注解
注解说明
@Component使用在类上用于实例化Bean
@Controller使用在web层类上用于实例化Bean
@Service使用在service层类上用于实例化Bean
@Repository使用在dao层类上用于实例化Bean
@Autowired使用在字段上用于根据类型依赖注入
@Qualifer结合@Autowired一起使用在字段是用于根据名称依赖注入
@Resource相当于@Autowired+@Qualifer,按照名称进行注入
@Value注入普通属性
@Scope标注Bean的作用范围
@PostConstruct使用在方法上标注该方法是Bean的初始化方法
@PreDestroy使用在方法上标注该方法是Bean的销毁方法
(2)新注解

使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:

  • 非自定义的Bean的配置:<bean>

  • 加载properties文件的配置: <context:property-placeholder>

  • 组件扫描的配置:<context:component-scan>

  • 引入其他配置文件:<import>

注解说明
@Configuration用于指定当前类是一个Spring配置类,当创建容器时会从该类上加载注解
@ComponentScan用于指定Spring在初始化容器时要扫描的包。 作用和在Spring的xml配置文件中的<context:component-scan base-package="cn.edu.cqie"/>一样
@Bean使用在方法上,标注将该方法的返回值存储到Spring容器中
@PropertySource用于加载.properties文件中的配置
@Import用于导入其他配置类

2.建立数据库连接

 (1).创建数据库gcxy_teach,并按以下sql创建表格
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `phone`
-- ----------------------------
DROP TABLE IF EXISTS `phone`;
CREATE TABLE `phone` (
  `phone_id` bigint NOT NULL AUTO_INCREMENT COMMENT '手机编号',
  `brand_id` bigint NOT NULL COMMENT '品牌编号',
  `model_number` varchar(50) COLLATE utf8mb4_general_ci NOT NULL COMMENT '型号',
  `capacity` int NOT NULL COMMENT '存储容量',
  PRIMARY KEY (`phone_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ----------------------------
-- Records of phone
-- ----------------------------
INSERT INTO `phone` VALUES ('1', '1', 'mate60', '256');
INSERT INTO `phone` VALUES ('2', '1', 'p60', '128');
INSERT INTO `phone` VALUES ('3', '2', 'x50', '128');
(2).导入项目所需坐标
 <dependencies>
        <!--        spring相关坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.8</version>
        </dependency>
        <!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <!--        spring整合jdbc相关坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.8</version>
        </dependency>
        <!--        spring整合junit相关坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.8</version>
        </dependency>
        <!--        druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!--        junit测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.5.1</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
(3)在resources文件夹下创建文件jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///gcxy_teach?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

(4)创建Spring配置类使用@PropertySource注解加载properties文件

@Configuration
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {

   
}
(5)使用@Bean注解配置数据源(连接池)
@Configuration
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {

    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.driver}")
    private String driverClassName;

    @Bean
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(jdbcUrl);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);
        hikariConfig.setDriverClassName(driverClassName);
        return new HikariDataSource(hikariConfig);
    }

}
 
(6)编写测试类和测试方法进行测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class DataSourceTest {

    @Autowired
    private DataSource dataSource;

    @Test
    public void testDataSource() throws SQLException {
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

3.配置使用JdbcTemplate从数据库中查询数据

(1)在com.cqgcxy.entity包下创建实体类
public class Phone {
//    phone_id	bigint
    private Long phoneId;
//    brand_id	bigint
    private Long brandId;
//    model_number	varchar
    private String modelNumber;
//    capacity	int
    private Integer capacity;

    public Long getPhoneId() {
        return phoneId;
    }

    public void setPhoneId(Long phoneId) {
        this.phoneId = phoneId;
    }

    public Long getBrandId() {
        return brandId;
    }

    public void setBrandId(Long brandId) {
        this.brandId = brandId;
    }

    public String getModelNumber() {
        return modelNumber;
    }

    public void setModelNumber(String modelNumber) {
        this.modelNumber = modelNumber;
    }

    public Integer getCapacity() {
        return capacity;
    }

    public void setCapacity(Integer capacity) {
        this.capacity = capacity;
    }

    @Override
    public String toString() {
        return "Phone{" +
                "phoneId=" + phoneId +
                ", brandId=" + brandId +
                ", modelNumber='" + modelNumber + '\'' +
                ", capacity=" + capacity +
                '}';
    }
}
(2)使用@Bean标签配置JdbcTemplate到spring容器中
@Configuration
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {

    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.driver}")
    private String driverClassName;

    @Bean
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(jdbcUrl);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);
        hikariConfig.setDriverClassName(driverClassName);
        return new HikariDataSource(hikariConfig);
    }

    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(dataSource);
        return jt;
    }
}
(3)在DataSourceTest测试类中编写测试方法testJdbcTemplate进行测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringConfigurationTest extends TestCase {

    @Autowired
    private JdbcTemplate jt;


    @Test
    public void testJdbcTemplate(){
        List<Phone> phoneList = jt.query("select * from phone", new BeanPropertyRowMapper<Phone>(Phone.class));
        phoneList.forEach(s-> System.out.println(s));
    }
}

4. 搭建三层架构:

(1)创建数据访问层:dao接口和实现类:
  • 在com.cqgcxy.dao包下创建PhoneDao接口

public interface PhoneDao {
    List<Phone> select();
}
  • 在com.cqgcxy.dao.impl包下创建PhoneDaoImpl实现类。

@Repository
public class PhoneDaoImpl implements PhoneDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Phone> select() {
        return jdbcTemplate.query("select * from phone", new BeanPropertyRowMapper<Phone>(Phone.class));
    }
}
(2)创建业务逻辑层:service接口和实现类
  • 在com.cqgcxy.service包下创建PhoneService接口

public interface PhoneService {
    List<Phone> getPhones();
}
  • 在com.cqgcxy.service.impl包下创建PhoneServiceImpl实现类。

@Service
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private PhoneDao phoneDao;

    public List<Phone> getPhones() {
        return phoneDao.select();
    }
}
 (3)创建表示层:在com.cqgcxy.controller包下controller类
@Controller
public class PhoneController {
    @Autowired
    private PhoneService phoneService;

    public List<Phone> getAll() {
        return phoneService.getPhones();
    }
}
 (4)在Spring的配置类上面配置注解扫描。
@Configuration
@PropertySource("classpath:jdbc.properties")
@ComponentScan(basePackages = "com.cqgcxy") // 修改成你的包路径
public class SpringConfiguration {

    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.driver}")
    private String driverClassName;

    @Bean
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(jdbcUrl);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);
        hikariConfig.setDriverClassName(driverClassName);
        return new HikariDataSource(hikariConfig);
    }

    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(dataSource);
        return jt;
    }
}
(5)选中PhoneController类,按ctrl+shift+T为该类创建对应的JUnit4的测试类和测试方法。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class PhoneControllerTest {

    @Autowired
    private PhoneController phoneController;

    @Test
    public void getAll() {
        List<Phone> phoneList = phoneController.getAll();
        phoneList.forEach(s-> System.out.println(s));
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值