第一个spring入门案例

1. 为什么需要spring?

如果A组件依赖于B组件,那么这样new的话,则硬编码的耦合度高。

使用spring的依赖注入,面向接口编程,防止了硬编码的耦合。

使用spring的aop的面向切面编程,使其更加的具有拓展性。

 

2. 第一个使用spring的案例

package com.huxin.springfirst.dao;

public interface Axe {
    public void chop();
}

 

package com.huxin.springfirst.dao.impl;

import com.huxin.springfirst.dao.Axe;

public class StoneAxe implements Axe {
    public StoneAxe(){
    	System.out.println("石头已经被创建");
    }
	public void chop() {
		System.out.println("石头做的东西真是不好啊");
	}
}


 

package com.huxin.springfirst.service;

public interface Person {
    public void userAxe();
}


 

package com.huxin.springfirst.service.impl;
import com.huxin.springfirst.dao.Axe;
import com.huxin.springfirst.service.Person;
public class Chinese implements Person {
    private Axe axe;
    
//	public Axe getAxe() {
//		return axe;
//	}
//
//	public void setAxe(Axe axe) {
//		this.axe = axe;
//	}
    public Chinese(Axe axe){
    	System.out.println("我被创建");
    	this.axe = axe;
    }
    
	public void userAxe() {
        axe.chop();
	}
	
	public void close(){
		System.out.println("人的这个bean被销毁");
	}
}


 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
       
      
      <bean id="stoneAxe"  class="com.huxin.springfirst.dao.impl.StoneAxe"/>
      <bean id="chinese"  class="com.huxin.springfirst.service.impl.Chinese" destroy-method="close">
            <!-- <property name="axe"  ref="stoneAxe"/> -->
            <constructor-arg ref="stoneAxe"/>
      </bean>     
</beans>


 

package com.huxin.springfirst.test;

import junit.framework.TestCase;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.huxin.springfirst.service.Person;

public class Test extends TestCase {
    public void test1(){
    	AbstractApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    	Person person = (Person) ac.getBean("chinese");
    	person.userAxe();
    	ac.registerShutdownHook();
    }
}


 


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值