Spring 基础
首先Spring提供的功能有:
Inversion of control (IOC): Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application objects.
MVC Framework: Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
Spring 步骤
在Eclipse下新建立一个java工程,将Spring包导入工程。
新建立一个ShowMessage文件,内容如下:
package test;
/**
* @author caiji
*
*/
public class ShowMessage {
//msg information
private String message;
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return this.message;
}
//the way to send msg
public void show(){
System.out.print("---Message---" + getMessage());
}
}
新建立一个myspring.xml文件,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 定义了ShowMessage类的bean -->
<bean id = "myBean" class="test.ShowMessage">
<property name="message">
<value>Hello Spring!</value>
</property>
</bean>
</beans>
建立一个Mytest文件,代码如下:
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* @author caiji
*
*/
public class Mytest {
public static void main(String argv[]){
//get Spring context
ApplicationContext ctx = new FileSystemXmlApplicationContext("sys/myspring.xml");
//get myBean in context
ShowMessage sm = (ShowMessage)ctx.getBean("myBean");
//show msg
sm.show();
}
}
对应的包和目录没有说明,可以参照程序。运行Mytest文件,可以看到如下运行结果:
---Message---Hello Spring!
参考:
http://www.tutorialspoint.com/spring/spring_interview_questions.htm