1, the introduction of Spring.jar package.
2, write code
Description: These classes and XML configuration files are in the same package "Springtest"
Interface Class Tinterface.java
Public interface Tinterface {
Public String getName ();
}
Interface Implementation Class Timpl.java
public class Timpl implements tinterface{
Public String GetName () {
Return ' This is Spring test ';
}
}
IOC Invoke Class Tservice.java
public class TService {
Public String printname (Tinterface tinter) {
System.out.println ("TService:" +tinter.getname ());
Return "Success";
}
}
XML configuration File Beans.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE beans Public "-//spring//dtd bean//en"
"Http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<bean id= "Springtest" class= "Springtest". Timpl "></bean>
</beans>
Test Main class Test.java
Public class Test {
public static void Main (string[] args) {
// ApplicationContext ac = new Classpathxmlapplicationcontext ("Springtest/beans.xml");
// ApplicationContext ac = new Classpathxmlapplicationcontext ("File:F :/netbeans project/testweb/build/web/web-inf/classes/springtest/beans.xml ");
// ApplicationContext ac = new Filesystemxmlapplicationcontext ("Build/web/web-inf/classes/springtest/beans.xml");
// ApplicationContext ac = new Filesystemxmlapplicationcontext ("F:/ NetBeans Project/testweb/build/web/web-inf/classes/springtest/beans.xml ");
Resource Resource = new Classpathresource ("Springtest/beans.xml");
beanfactory ac = new Xmlbeanfactory (Resource);
Tinterface tinter = (tinterface) ac.getbean ("Springtest");
TService tservice = new TService ();
System.out.println (Tservice.printname (tinter));
}
}
Run-time results are normal, no abnormal situation
Note: How to obtain the XML configuration file path:
for Classpathxmlapplicationcontext (), classpath: prefix is not required, default refers to the project Classpath path below If you want to use an absolute path, you need to add a file: prefix to indicate that this is an absolute path;
for Filesystemxmlapplicationcontext (), the default representation is two:
1, the project's working path, the root directory of the project, and the
2, has a disk character that represents the absolute path of the file. &NBSP
If you want to use the classpath path, you need a prefix classpath.