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的另一种表现形式,组件以一些预先定义好的方式接受来自如容器的资源注入