首先将Spring所需要的包导入:
首先是带xml的方式
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="hw" class="com.yc.spring.HelloWorld" scope="prototype">
</bean>
</beans>
HelloWorld.class:
package com.yc.spring;
import org.springframework.stereotype.Component;
public class HelloWorld {
public HelloWorld(){
System.out.println("helloworld的构造函数");
}
public void say(){
System.out.println("helloworld spring");
}
}
下面是使用注解方式:
package com.yc.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//用这个类来代替xml文件
@Configuration
@ComponentScan("com.yc")
public class Appconfig {
}
HelloWorld.class:
package com.yc.spring;
import org.springframework.stereotype.Component;
@Component //注解方式所需要的
public class HelloWorld {
public HelloWorld(){
System.out.println("helloworld的构造函数");
}
public void say(){
System.out.println("helloworld spring");
}
}
Test.class:
package spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.yc.spring.Appconfig;
import com.yc.spring.HelloWorld;
import junit.framework.TestCase;
public class Test extends TestCase {
public void testApp(){//传统方式
HelloWorld hw=new HelloWorld();
hw.say();
}
public void testApp02(){//spring 控制反转方式
//1读取sring.xml文件 创建spring容器(完成helloWorld对象的创建)
ApplicationContext con=new ClassPathXmlApplicationContext("spring.xml");
HelloWorld hw=(HelloWorld) con.getBean("hw");
hw.say();
}
//注解方式
public void testApp03(){//spring 控制反转方式
//1读取sring.xml文件 创建spring容器(完成helloWorld对象的创建)
ApplicationContext con=new AnnotationConfigApplicationContext(Appconfig.class);
//HelloWorld hw=con.getBean(HelloWorld.class);//这样就产生了依赖,必须有HelloWorld这个类
//hw.say();
HelloWorld hw=(HelloWorld) con.getBean("helloWorld");//约定为类名第一个字母为小写 最前面的HelloWorld可面向接口 不产生依赖
hw.say();
}
}