1、基础概念
IOC有三种注入方式:
1、构造方法注入,就是通过构造方法进行实例化成员属性对象,优点是实现对象之后直接就可以使用,但是参数过多也是个麻烦
2、setter方法注入,实现相应的setter方法,外界就可以使用set方法进行注入,这个比较方便,缺点是创建对象之后不能马上使用
3、接口注入,实现指定接口中的方法进行注入(不提倡)
2、配置spring测试
设置配置文件
<?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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="cn.cutter" /> </beans>
测试代码:
package spring; import java.io.File;
import java.io.IOException;
import java.net.URL; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.cutter.start.provider.FXNewsProvider; public class SpringTest { @Test
public void test1() throws IOException {
String path = FXNewsProvider.class.getResource("").getPath();
File f = new File("E:/Github/bishi/java/project/cutter-point-spring Maven Webapp/src/main/resources/application-bean.xml");
String path2 = f.getCanonicalPath();
URL path3 = FXNewsProvider.class.getResource(""); System.out.println(path);
System.out.println(path2);
System.out.println(path3); ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:application-bean.xml");
FXNewsProvider fxNewsProvider = (FXNewsProvider) ctx.getBean("FXNewsProvider");
if(fxNewsProvider != null) {
System.out.println("ok");
}
} }
结果展示: