深入浅出Spring框架:从入门到精通

一、Spring框架的诞生和核心思想

Spring框架的出现,是为了解决Java EE开发中的痛点,如代码耦合度高、重复代码多、配置繁琐等问题。它提供了一套完整的解决方案,将对象的创建、依赖关系的管理、事务管理等职责交给容器来处理,实现了代码的解耦,提高了开发效率和应用程序的可维护性。

 

二、Spring的核心思想:IoC和DI

Spring的核心思想是控制反转 (IoC) 依赖注入 (DI)

  • IoC (控制反转): 将对象的创建和依赖关系的维护交给Spring容器来管理,开发者不再需要手动创建对象,而是从容器中获取对象,从而实现了控制权的反转。
  • DI (依赖注入): 容器负责将依赖的对象注入到目标对象中,开发者无需手动编写代码来设置依赖关系,从而实现了依赖关系的解耦。

IoC和DI是Spring的核心和灵魂,它们贯穿于Spring框架的各个模块,为开发者提供了一套完整的开发解决方案。

 

三、Spring的核心体系:构建Java应用程序的基石

Spring框架的核心体系由以下几个模块组成:

  • 核心容器: 包括Spring-core、Spring-beans、Spring-context等模块,负责对象的创建、依赖注入、生命周期管理等功能。
  • AOP模块: 提供面向切面编程的实现,用于将横切关注点(例如日志记录、事务管理)与业务逻辑代码分离,提高代码可读性和可维护性。
  • 数据访问/集成: 包括JDBC、ORM、JMS等模块,提供数据访问和集成方案,简化数据库操作和消息队列的使用。
  • Web模块: 包括Spring MVC、WebSocket等模块,提供Web开发功能,简化Web应用程序的开发流程。
  • 其他模块: 包括JMS、Email、任务调度等模块,提供其他功能支持。

这些模块共同构成了Spring框架的核心体系,为开发者提供了构建Java应用程序的基石。

 

四、Spring Bean工厂和IoC容器:对象的创建和管理

Spring Bean工厂是Spring框架的核心组件之一,负责对象的创建、依赖注入、生命周期管理等功能。它实现了IoC思想,将对象的创建和依赖关系的管理交给容器来处理。

Spring IoC容器是Spring框架的另一个核心组件,负责管理Bean对象的生命周期,包括创建、初始化、销毁等。它提供了多种类型的容器,例如BeanFactory和ApplicationContext。

BeanFactory是Spring框架的基础容器,它提供了IoC和DI的基本功能。ApplicationContext是BeanFactory的子接口,它提供了更多的高级功能,例如国际化、事件传播、资源加载等。

 

五、Spring实例化对象的几种方式

Spring提供了多种实例化对象的方式,包括:

  • 构造方法实例化: 通过构造方法创建对象,可以是无参构造方法或有参构造方法。
  • 工厂方式实例化: 通过工厂类创建对象,可以是静态工厂或实例工厂。
  • 实现FactoryBean规范: 通过实现FactoryBean接口创建对象,这种方式是延迟创建Bean对象。

开发者可以根据不同的场景选择合适的实例化方式。

示例代码:

// 通过构造方法实例化对象
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

// 通过静态工厂实例化对象
public class StudentFactory {
    public static Student createStudent(String name, int age) {
        return new Student(name, age);
    }
}

// 通过实例工厂实例化对象
public class StudentFactory {
    private String school;

    public StudentFactory(String school) {
        this.school = school;
    }

    public Student createStudent(String name, int age) {
        return new Student(name, age, school);
    }
}

// 通过FactoryBean规范实例化对象
public class StudentFactoryBean implements FactoryBean<Student> {
    @Override
    public Student getObject() throws Exception {
        return new Student("张三", 20);
    }

    @Override
    public Class<?> getObjectType() {
        return Student.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

 

六、Spring依赖注入的几种方式

Spring提供了多种依赖注入的方式,包括:

  • Set方式注入: 通过Set方法注入依赖对象。
  • 构造器方式注入: 通过构造方法注入依赖对象。
  • 自动装配: 自动注入依赖对象,可以是按类型或按名称注入。
  • 不同类型的值如何注入: 可以注入普通数据、引用数据、集合数据等。

开发者可以根据不同的需求选择合适的依赖注入方式。

示例代码:

// Set方式注入
public class StudentService {
    private StudentDao studentDao;

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
}

// 构造器方式注入
public class StudentService {
    private StudentDao studentDao;

    public StudentService(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
}

// 自动装配
public class StudentService {
    @Autowired
    private StudentDao studentDao;
}

 

七、Spring配置文件其它标签

Spring配置文件除了<bean>标签外,还有其他一些标签,例如:

1. <beans> 标签

  • 作用: 作为xml配置的根标签,用于包裹其他Spring配置标签。
  • 示例:
<beans>
    <!-- ... 其他配置标签 ... -->
</beans>

2. <import> 标签

  • 作用: 用于导入其他配置文件,可以将配置分散到不同的文件中,提高可维护性。
  • 示例:
<beans>
    <import resource="classpath:applicationContext-dao.xml"/>
    <import resource="classpath:applicationContext-service.xml"/>
</beans>

 

3. 自定义标签

  • 作用: 通过引入xsd文件,可以自定义标签,实现更灵活的配置方式。
  • 示例:
<!-- 自定义标签的xsd文件 -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="myTag">
        <xs:complexType>
            <xs:attribute name="name" type="xs:string"/>
            <xs:attribute name="value" type="xs:string"/>
        </xs:complexType>
    </xs:element>
</xs:schema>

<!-- 使用自定义标签 -->
<beans>
    <myTag name="自定义标签的名称" value="自定义标签的值"/>
</beans>

4. <bean> 标签的其他属性

除了基本的 classidname 属性外,<bean> 标签还支持以下属性:

  • scope: 指定Bean的作用域,例如 singleton (默认)、prototyperequestsession 等。
  • lazy-init: 指定Bean的延迟初始化,例如 true (延迟加载)、false (立即加载)。
  • init-method: 指定Bean的初始化方法,在Bean创建后调用。
  • destroy-method: 指定Bean的销毁方法,在Bean销毁前调用。

5. <property> 标签

  • 作用: 用于注入依赖对象,可以是普通数据、引用数据、集合数据等。
  • 示例:
<bean id="studentService" class="com.example.StudentService">
    <property name="studentDao" ref="studentDao"/>
    <property name="list" value="value1,value2,value3"/>
    <property name="map">
        <map>
            <entry key="key1" value="value1"/>
            <entry key="key2" value="value2"/>
        </map>
    </property>
</bean>

6. <constructor-arg> 标签

  • 作用: 用于注入构造方法参数,可以是无参构造方法或有参构造方法。
  • 示例:
<bean id="studentService" class="com.example.StudentService">
    <constructor-arg ref="studentDao"/>
    <constructor-arg value="value1"/>
</bean>

7. <property> 和 <constructor-arg> 的区别

  • <property>: 用于注入Set方法参数,可以是无参构造方法或有参构造方法。
  • <constructor-arg>: 用于注入构造方法参数,只能是有参构造方法。

8. <list><map><set><props> 标签

  • <list>: 用于注入List集合数据。
  • <map>: 用于注入Map集合数据。
  • <set>: 用于注入Set集合数据。
  • <props>: 用于注入Properties集合数据。

9. <bean> 标签的继承

  • 作用: 可以将一个 <bean> 标签的内容继承到另一个 <bean> 标签中。
  • 示例:
<!-- 父Bean -->
<bean id="parent" class="com.example.Parent">
    <property name="name" value="parent"/>
</bean>

<!-- 子Bean -->
<bean id="child" parent="parent">
    <property name="age" value="20"/>
</bean>

10. <bean> 标签的别名

  • 作用: 可以给 <bean> 标签指定别名,方便在容器中获取Bean对象。
  • 示例:
<bean id="studentService" class="com.example.StudentService" alias="studentServiceAlias"/>

11. <bean> 标签的初始化和销毁

  • 作用: 可以指定Bean的初始化和销毁方法。
  • 示例:
<bean id="studentService" class="com.example.StudentService">
    <init-method>initMethod</init-method>
    <destroy-method>destroyMethod</destroy-method>
</bean>

 

八、Spring常用注解

Spring注解提供了一种更加简洁和直观的方式来配置Spring容器,取代了传统的XML配置文件。这些注解使得代码更加易读,易于维护,并提高了开发效率。

1. @Component

  • 作用: 将类交给Spring容器管理,相当于XML配置中的 <bean> 标签。
  • 示例:
@Component
public class Student {
    // ...
}

2. @Controller

  • 作用: 将类标记为控制器,相当于XML配置中的 <bean class="com.example.StudentController"> 标签,并指定 scope="prototype"
  • 示例:
@Controller
public class StudentController {
    // ...
}

3. @Service

  • 作用: 将类标记为服务层,相当于XML配置中的 <bean class="com.example.StudentService"> 标签,并指定 scope="singleton"
  • 示例:
@Service
public class StudentService {
    // ...
}

4. @Repository

  • 作用: 将类标记为数据访问层,相当于XML配置中的 <bean class="com.example.StudentDao"> 标签,并指定 scope="singleton"
  • 示例:
@Repository
public class StudentDao {
    // ...
}

5. @Scope

  • 作用: 指定Bean的作用域,例如 singleton (默认)、prototyperequestsession 等。
  • 示例:
@Service
@Scope("prototype")
public class StudentService {
    // ...
}

6. @Lazy

  • 作用: 指定Bean的延迟初始化,例如 true (延迟加载)、false (立即加载)。
  • 示例:
@Service
@Lazy(true)
public class StudentService {
    // ...
}

7. @PostConstruct

  • 作用: 指定初始化方法,在Bean创建后调用。
  • 示例:
@Service
@PostConstruct
public void init() {
    // ...
}

8. @PreDestroy

  • 作用: 指定销毁方法,在Bean销毁前调用。
  • 示例:
@Service
@PreDestroy
public void destroy() {
    // ...
}

9. @Value

  • 作用: 注入普通数据,相当于XML配置中的 <property> 标签。
  • 示例:
@Service
public class StudentService {
    @Value("Hello World!")
    private String message;

    // ...
}

10. @Autowired

  • 作用: 注入引用数据,相当于XML配置中的 <property> 标签。
  • 示例:
@Service
public class StudentService {
    @Autowired
    private StudentDao studentDao;

    // ...
}

11. @Qualifier

  • 作用: 当使用 @Autowired 注解注入相同类型的多个Bean时,可以根据名称注入特定的Bean。
  • 示例:
@Service
public class StudentService {
    @Autowired
    @Qualifier("studentDaoImp")
    private StudentDao studentDao;

    // ...
}

12. @Resource

  • 作用: 根据类型或名称注入引用数据,类似于 @Autowired 和 @Qualifier 的组合。
  • 示例:
@Service
public class StudentService {
    @Resource(name = "studentDaoImp")
    private StudentDao studentDao;

    // ...
}

13. @Bean

  • 作用: 将方法标记为Bean定义,相当于XML配置中的 <bean> 标签。
  • 示例:
@Component
public class StudentFactory {
    @Bean
    public Student createStudent() {
        return new Student("张三", 20);
    }
}

14. @Configuration

  • 作用: 将类标记为配置类,相当于XML配置文件。
  • 示例:
@Configuration
public class StudentConfig {
    @Bean
    public Student createStudent() {
        return new Student("张三", 20);
    }
}

15. @ComponentScan

  • 作用: 指定组件扫描的包路径,相当于XML配置中的 <context:component-scan> 标签。
  • 示例:
@Configuration
@ComponentScan("com.example")
public class StudentConfig {
    // ...
}

16. @PropertySource

  • 作用: 指定属性文件的位置,相当于XML配置中的 <context:property-placeholder> 标签。
  • 示例:
@Configuration
@PropertySource("classpath:application.properties")
public class StudentConfig {
    // ...
}

17. @Import

  • 作用: 导入其他配置类,相当于XML配置中的 <import> 标签。
  • 示例:
@Configuration
@Import(StudentConfig.class)
public class StudentConfig {
    // ...
}

 

总结

 全面掌握Spring框架的各个方面,并将其应用到实际开发中,才能构建出结构清晰、功能强大、易于维护的Java应用程序。

  • 21
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值