Spring4 HelloWorld

Spring4 HelloWorld

Spring是一个轻量级框架,以IOC(控制反转),AOP(面向切面)为内核,致力于JavaEE应用各层的解决方案
  1. 创建一个实体类,且拥有无参构造器
  2. 创建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>
  1. 测试
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的另一种表现形式,组件以一些预先定义好的方式接受来自如容器的资源注入

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值