ssm-spring入門
Spring框架是一個開放源代碼的J2EE應用程式框架,由Rod Johnson發起,是針對bean的生命周期進行管理的輕量級容器(lightweight container), Spring解決了開發者在J2EE開發中遇到的許多常見的問題,提供了功能強大IOC、AOP及Web MVC等功能,以 IoC(Inverse of Control,控制反轉)和 AOP(Aspect Oriented Programming,面向切面編程)為內核,是Spring全家桶(Spring framework、SpringMVC、SpringBoot、Spring Cloud、Spring Data、Spring Security 等)的基礎和核心,
初識Spring
從簡單工程入手:- 創建物體類:
- resources目錄下創建spring配置xml檔案:
- 測驗:
<?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">
<bean id="student" />
</beans>
每個bean代表一個物體,id是別名,class是類全稱,
@Test
public void student() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
}
ClassPathXmlApplicationContext: 讀取裝配spring xml組態檔,運行結果如下:

可以看出在裝配完spring xml組態檔后,物體類構造方法就已經創建,
依賴注入:
IOC(控制反轉)是spring框架的核心思想之一,而這一思想的重要實作方式是DI(依賴注入),依賴注入原理是使用反射,在上訴的例子上用依賴注入來獲取實體:- 修改spring組態檔:beans.xml
- 通過組態檔獲取該實體
- 查看結果
<bean id="student" >
<property name="id" value="https://www.cnblogs.com/zhoux123/p/123"/>
<property name="name" value="https://www.cnblogs.com/zhoux123/p/張三"/>
</bean>
這個組態檔中,宣告了一個物體物件student,并對其屬性id,name進行了賦值,
@Test
public void student() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
}
獲取實體的核心方法是:context.getBean("student"),其原理是BeanFactory通過反射獲取,

使用注解
上面介紹了使用組態檔注入物件的方式,接下來看看如何使用注解來注釋物件:- 修改spring組態檔:beans.xml
- 在物體上添加注解:
- 查看結果

要使用注解,首先要添加注解的支持:
<context:annotation-config/>其次添加掃描包名:
<context:component-scan base-package="com.zx.demo.spring.beans"/>

這里用到了兩個注解:
@Component @Value,其中Component對應<bean>標簽,Value對應<property>標簽整個注解等同于:
<bean id="student" >
<property name="id" value="https://www.cnblogs.com/zhoux123/p/123"/>
<property name="name" value="https://www.cnblogs.com/zhoux123/p/張三"/>
</bean>

和使用組態檔注入得到相同效果,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/295982.html
標籤:Java
