[英]Why should I use Spring core framework over java application
我是Spring框架的新手。我使用Spring框架制作了一个简单的“ HelloSpring”应用程序。
POJO CLASS :-
public class HelloSpring {
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
Beans.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-3.0.xsd">
<bean id="helloSpring" class="com.dash.abinash.SpringHelloApp.HelloSpring">
<property name="message" value="Hello World!" />
</bean>
Client.java:-
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ClientApp {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloSpring obj = (HelloSpring) context.getBean("helloSpring");
System.out.println(obj.getMessage());
}
}
输出:-
Sep 27, 2017 12:02:58 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4534b60d: startup date [Wed Sep 27 12:02:58 IST 2017]; root of context hierarchy
Sep 27, 2017 12:02:58 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
Hello World!
但是同样的输出,我也将通过使用抽象和封装概念(getter和setter)方法来获得Spring框架。
HelloSpring ref=new HelloSpring();
ref.setMessage("Hello World!");
System.out.println("Output without Spring framework "+ref.getMessage());
然后,为什么要使用Spring框架。 也许这是一个愚蠢的问题,但如果可能的话,请尝试向我详细说明。
就像这样:当您这样做时:
HelloSpring ref=new HelloSpring();
ref.setMessage("Hello World!");
System.out.println("Output without Spring framework "+ref.getMessage());
您每次都在创建类的实例。
但是在企业应用程序(Web应用程序)中,您需要记住,这种方法对服务器不利。 因此,例如,这里有Spring部分,您可以使用@service,并且一次声明HelloSpring(就像服务一样),并且每次您希望使用HelloSpring时都不必在服务器内存中放置其他位置。
喜欢:
@Service
public class HelloSpring{
...
...
}
正如@Yuval在评论中提到的那样,Spring提供了许多工具。 您只需要阅读文档,并找到对您的应用程序有益的内容。
最好
在您的示例中,它的1类用于打印某些消息。 因此您已使用new运算符创建了对象。 但是在企业应用程序中,业务逻辑将在多个java类中实现。 在这种情况下,如果您每次都创建新的Java实例,则内存将用完并且服务器将关闭。 为了解决这个问题,我们参考了依赖注入设计模式。 Spring框架是基于这种模式构建的,旨在解决上述实时问题。 如果您感兴趣,请阅读一些教程,在春季还可以使用更多有用的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.