XML配置方
优点:便于阅读、与业务代码解耦
缺点:解析XML影响性能、开发工作量大,编译器不可校验配置正确性
注解配置方式
优点:开发便捷、编译期可校验配置正确性
缺点:注解与代码绑定,配置分散,不利于统一处理
Java配置方式
优点:编译期可校验配置正确性、配置简单,方便维护和管理、可以使用IDE的代码提示功能
缺点:不利于新人学习和理解框架的原理
实现Java配置的方式,主要通过两个注解:@Configuration和@Bean
@Configuration
标注于类上,表示该类为配置类,具有与Spring IoC配置文件相同的功能
@Bean
标注于配置类的方法上,用于向该配置类注入一个Bean组件
方法返回值为组件的对象类型
演示案例
- 实体类
-
- public class Dog {
-
- private String name;//宠物狗狗的姓名
-
- private int age;//宠物狗狗的年龄
-
- //此处省略getter and setter 方法
-
- }
-
- public class User {
-
- private String userName;
-
- private Dog dog;
-
- //此处省略getter and setter 和 toString方法
-
- }
-
-
- 配置类
-
- /**
-
- * @Configuration 指明当前类是一个配置类,就是来代替之前的Spring配置文件
- * 在配置文件中用
标签添加组件 - */
- @Configuration
-
- public class JavaConfig {
-
- //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
-
- //@Bean
-
- //@Bean注解提供了name属性,通过name属性可以指定Bean组件的id值
-
- @Bean(name = "user13")
-
- public User user12(){
-
- User user=new User();
-
- user.setUserName("小明");
-
- Dog dog=new Dog();
-
- dog.setName("欢欢");
-
- dog.setAge(5);
-
- user.setDog(dog);
-
- return user;
- }
- }
-
-
-
-
-
- 测试类
-
- @RunWith(SpringRunner.class)
-
- @SpringBootTest
-
- class Ch041javapeizhiApplicationTests {
-
- @Test
- void contextLoads() {
-
- /*java配置的方式生成的Spring容器。测试时,首先通过AnnotationConfigApplicationContext
-
- 获取SpringIoc容器的上下文信息。再在上下文信息中获取对应的Bean组件*/
-
- ApplicationContext act=new AnnotationConfigApplicationContext(JavaConfig.class);
-
- User user=(User)act.getBean("user13");
-
- System.out.println(user.toString());
-
- }
-
- @Resource
-
- private User user;
-
- @Test
-
- void contextLoads2() {
-
- System.out.println(user.toString());
-
- }
-
- }
Java配置方式扩展
Bean组件的作用域:@Scope注解可以标注在方法上与@Bean注解搭配使用
@Scope("singleton") :默认,单例模式,容器只创建一次实例
@Scope("prototype") :每次获取时创建新的实例
initMethod属性
作用:被标注的方法将于容器启动前执行
使用方法:@Bean(initMethod="Bean中的初始化方法名")
destroyMethod属性
作用:被标注的方法将于容器销毁前执行
使用方法:@Bean(destroyMethod="Bean中的销毁方法名")
SpringBoot整合MyBatis的方式有两种,根据引入依赖的名称:分为mybatis-spring的方式 和 mybatis-spring-boot-starter的方式。
方式1:mybatis-spring方式
创建SpringBoot项目,搭建项目结构如图:

-
- 实体类----------------------------------------
-
- public class User {
-
- private Integer id;
-
- private String userName;
-
- private String userPassword;
-
- //此处省略getter and setter
-
- }
-
-
-
-
- mapper类----------------------------------------
-
- public interface UserMapper {
-
- //根据id查询对应的用户信息
-
- User getUserById(Long id);
-
- }
-
-
-
- mapper映射文件----------------------------------------
-
- <mapper namespace="com.msds.mapper.UserMapper">
-
- <!--根据id查询对应的用户信息-->
-
- <select id="getUserById" resultType="user" parameterType="long">
-
- select * from `smbms_user`
-