Spring-IOC容器注解方式整合三层架构

注解方式特点

//1. 完全注解方式指的是去掉xml文件,使用配置类 + 注解实现
//2. xml文件替换成使用@Configuration注解标记的类
//3. 标记IoC注解:@Component,@Service,@Controller,@Repository 
//4. 标记DI注解:@Autowired @Qualifier @Resource @Value
//5. <context:component-scan标签指定注解范围使用@ComponentScan(basePackages={"com.atguigu.components"})替代
//6. <context:property-placeholder引入外部配置文件使用      @PropertySource({"classpath:application.properties","classpath:jdbc.properties"})替代
//7. <bean 标签使用@Bean注解和方法实现
//8. IoC具体容器实现选择AnnotationConfigApplicationContext对象

案例:

搭建一个三层架构案例,模拟查询全部学生(学生表)信息,持久层使用JdbcTemplate和Druid技术,使用注解+配置类方式进行组件管理

1.数据库准备

-- ----------------------------
-- Table structure for students
-- ----------------------------
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students`  (
  `id` int NOT NULL,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `gender` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `age` int NULL DEFAULT NULL,
  `class` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of students
-- ----------------------------
INSERT INTO `students` VALUES (1, '喜羊羊', '男', 18, '高中一班');
INSERT INTO `students` VALUES (2, '美羊羊', '女', 19, '高中二班');
INSERT INTO `students` VALUES (3, '懒羊羊', '男', 18, '高中一班');
INSERT INTO `students` VALUES (4, '沸羊羊', '男', 18, '高中三班');
INSERT INTO `students` VALUES (5, '暖羊羊', '女', 19, '高中二班');
INSERT INTO `students` VALUES (6, '软绵绵', '男', 60, '高中一班');
INSERT INTO `students` VALUES (7, '灰太狼', '男', 30, '高中三班');
INSERT INTO `students` VALUES (8, '红太狼', '女', 30, '高中二班');

SET FOREIGN_KEY_CHECKS = 1;

2.项目准备

        1.项目创建
        2. pojo包下创建实体类Student
@Setter//使用lombok,实现set方法
public class Student {

    private Integer id;
    private String name;
    private String gender;
    private Integer age;
    private String classes;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", classes='" + classes + '\'' +
                '}';
    }
}
        3.三层架构搭建和实现
                a.持久层
public interface StudentDao {

    List<Student> queryAll();
}


public class StudentDaoImpl  implements StudentDao {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Student> queryAll() {

        String sql = "select id , name , age , gender , class as classes from students ;";

        /*
          query可以返回集合!
          BeanPropertyRowMapper就是封装好RowMapper的实现,要求属性名和列名相同即可
         */

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
    }
}
                b.业务层
public interface StudentService {
    List<Student> findAll();
}


@Service
public class StudentServiceImpl  implements StudentService{
    private StudentDao studentDao;

    @Override
    public List<Student> findAll() {
        List<Student> studentList = studentDao.queryAll();
        return studentList;
    }

    @Autowired
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
}
                c.表述层
@Controller
public class StudentController {
    private StudentService studentService;
    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    public void findAll(){
        List<Student> all = studentService.findAll();
        System.out.println("all = " + all);
    }
}
4.IOC配置类
// 标识这是一个 Java 配置类
@Configuration 
// 使用 ComponentScan 注解来扫描包 org.example
@ComponentScan(basePackages = "org.example")
// 使用 PropertySource 注解来加载 classpath:jdbc.properties 文件中的配置信息
@PropertySource("classpath:jdbc.properties") 
public class JavaConfig {

    @Bean // 定义一个数据源 bean
    public DataSource dataSource( // 注入 driver、url、username、password 等配置信息
                                  @Value("${cx.driver}") String driver,
                                  @Value("${cx.url}") String url,
                                  @Value("${cx.username}") String username,
                                  @Value("${cx.password}") String password) {

        // 创建一个 DruidDataSource 对象
        DruidDataSource dataSource = new DruidDataSource();
        // 设置驱动类名
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url); 
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        // 返回数据源 bean
        return dataSource;
    }

    @Bean // 定义一个 JdbcTemplate bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) { // 注入数据源 bean
        // 创建一个 JdbcTemplate 对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        // 设置数据源
        jdbcTemplate.setDataSource(dataSource); 
        return jdbcTemplate;
    }
}
5.测试包下运行测试
public class SpringIoCTest {
    @Test
    public void test(){
        //使用 AnnotationConfigApplicationContext 类初始化一个应用程序上下文对象,
        //同时指定了配置类 JavaConfig.class。
        //通过这个应用程序上下文对象直接获取 StudentController 类型的 bean 实例。
        //调用 controller 对象的 findAll() 方法,执行相应的操作
        StudentController controller = new AnnotationConfigApplicationContext(JavaConfig.class)
                .getBean(StudentController.class);
        controller.findAll();
    }
}
  • 13
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值