[英]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.