Spring4 HelloWorld
Spring是一個輕量級框架,以IOC(控制反轉),AOP(面向切面)爲內核,致力於JavaEE應用各層的解決方案
- 創建一個實體類,且擁有無參構造器
- 創建Spring配置文件:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
<!-- 配置bean
class: Bean的全類名,通過反射的方式在IOC容器中創建Bean,所有Bean中必須有無參構造器
id: 標識容器中的bean,id 唯一
-->
<bean id="helloWorld" class="com.java.spring.beans.Hello">
<!-- 通過set方法來配置bean -->
<property name="name" value="World"></property>
<property name="hello" value="Hello"></property>
</bean>
<bean id="helloWorld2" class="com.java.spring.beans.Hello">
<!-- 通過構造方法來配置bean
type: 可以指定參數類型
若要使用特殊字符可以使用:<![CDATA[特殊字符]]>
-->
<constructor-arg type="java.lang.String">
<value><![CDATA[<World^>]]></value>
</constructor-arg>
<constructor-arg value="Hello" type="java.lang.String"></constructor-arg>
</bean>
</beans>
- 測試
public class Main {
public static void main(String[] args) {
//創建Spring的IOC容器對象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//利用id從IOC容器中獲取Bean實例
Hello hello = (Hello) ctx.getBean("helloWorld2");
//利用類型返回IOC容器中的Bean,但IOC容器中只能有一個該類型的Bean
// Hello hello = ctx.getBean(Hello.class);
//調用方法
hello.hello();
}
}
IOC和DI
IOC:控制反轉。在Java開發中,IOC意味着將你設計好的類交給系統去控制,而不是在類裏面控制
DI:依賴注入。IOC的另一種表現形式,組件以一些預先定義好的方式接受來自如容器的資源注入