using Spring.Context.Support;
using System;
namespace SpringBase{
class Program {
static void Main(string[] args){
IoCMethod();
Console.ReadLine();
}
private static void IoCMethod() {
IApplicationContext ctx = ContextRegistry.GetContext("test");
IPersonDao dao = ctx.GetObject("PersonDao") as IPersonDao;
if (dao != null) {
dao.sayhello();
}
}
}
public class PersonDao : IPersonDao {
public void sayhello() {
Console.WriteLine("hello");
}
}
public interface IPersonDao{
void sayhello();
}
}
添加2个配置文件
app.config(如果是web项目肯定是web.config)
< xml version="1.0" encoding="utf-8" >
type="Spring.Context.Support.TypeAliasesSectionHandler, Spring.Core"/>
type="Spring.Context.Support.ContextHandler, Spring.Core" />
type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
objects.xml
当app.config的resource选择为注释掉的那一条的时候, 资源配置文件为当前目录下的objects.xml文件, 里面的xmlns属性是对节点的规范在vs中会自动提示节点
file://表示文件目录并且是相对于程序的目录
config://表示的是配置节点上的某个节点,
typeAliases表示type的别名,所以配置文件和xml文件上面的type参数不一样, 但是2个文件的效果是一样的
singleton参数表示这个实例是否为单例,默认为false
id为程序中所调用这个实例的name, 也可以设置为name="PersonDao" type="PersonDaoAlias"效果是一样的
当配置节点中context只有一个的时候可以不添加name属性, 程序中直接通过ContextRegistry.GetContext()获得程序的上下文
java篇(环境为Maven+Jdk1.7)
新建一个空的maven项目,在pom.xml文件配置
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
在META-INF下的MANIFEST.MF文件配置当main函数和引用的jar包
Manifest-Version: 1.0
Class-Path: lib/aopalliance-1.0.jar lib/commons-logging-1.1.1.jar lib/
spring-aop-3.2.4.RELEASE.jar lib/spring-beans-3.2.4.RELEASE.jar lib/s
pring-context-3.2.4.RELEASE.jar lib/spring-core-3.2.4.RELEASE.jar lib
/spring-expression-3.2.4.RELEASE.jar
Main-Class: springdemo.SpringBase
新建一个类一个接口一个main入口
IPersonDao.java
package springdemo;
public interface IPersonDao {
void sayhello();
}
PersonDao.java
package springdemo;
public class PersonDao implements IPersonDao {
public void sayhello() {
System.out.println("Hello World!");
}
}
SpringBase.java
package springdemo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringBase {
public static void main(String[] args) {
ApplicationContext ctx =
new FileSystemXmlApplicat