Development Tip

Spring Framework는 정확히 무엇입니까?

yourdevel 2020. 10. 2. 23:25
반응형

Spring Framework는 정확히 무엇입니까? [닫은]


저는 Spring대해 많이 듣습니다. 사람들은 Spring이 웹 개발을위한 좋은 프레임 워크라고 웹 전반에 걸쳐 말합니다. Spring Framework는 정확히 무엇입니까?


기본적으로 Spring은 매우 분리 된 시스템을 구축 할 수있는 패턴 인 위한 프레임 워크입니다 .

문제

예를 들어, 시스템 사용자를 나열하고 다음과 같은 인터페이스를 선언해야한다고 가정합니다 UserLister.

public interface UserLister {
    List<User> getUsers();
}

그리고 모든 사용자를 얻기 위해 데이터베이스에 액세스하는 구현 일 수도 있습니다.

public class UserListerDB implements UserLister {
    public List<User> getUsers() {
        // DB access code here
    }
}

보기에서 인스턴스에 액세스해야합니다 (예 : 기억하세요).

public class SomeView {
    private UserLister userLister;

    public void render() {
        List<User> users = userLister.getUsers();
        view.render(users);
    }
}

위의 코드는 변수를 초기화하지 않았습니다 userLister. 우리는 무엇을해야합니까? 다음과 같이 객체를 명시 적으로 인스턴스화하면 :

UserLister userLister = new UserListerDB();

...보기를 DB에 액세스하는 클래스의 구현과 결합합니다. DB 구현에서 쉼표로 구분 된 파일에서 사용자 목록을 가져 오는 다른 구현으로 전환하려면 어떻게해야합니까 (예제임을 기억하십시오)? 이 경우 다시 내 코드로 이동하여 마지막 줄을 다음과 같이 변경합니다.

UserLister userLister = new UserListerCommaSeparatedFile();

이와 같은 작은 프로그램에서는 문제가 없지만 ... 수백 개의 뷰와 비슷한 수의 비즈니스 클래스가있는 프로그램에서 어떤 일이 발생합니까? 유지 관리는 악몽이됩니다!

Spring (종속성 주입) 접근법

무엇 봄이 일은하는 것입니다 연결할 XML 파일이나 주석, 모든 객체 인스턴스화 및 스프링에 의해 초기화되며이 방법을 사용하여 클래스를 주입 적절한 장소 (서블릿, 웹 프레임 워크, 비즈니스 클래스, DAO를, 등, 등, 등로를 ...).

Spring의 예제로 돌아가서 userLister필드에 대한 setter가 있어야하고 다음과 같은 XML 파일이 있어야합니다.

<bean id="userLister" class="UserListerDB" />

<bean class="SomeView">
    <property name="userLister" ref="userLister" />
</bean>

또는 더 간단하게 뷰 클래스에있는 파일에 @Inject다음 같이 주석을 추가합니다 .

@Inject
private UserLister userLister;

뷰가 만들어집니다이 방법 마술은 해야합니다 UserLister작업을 준비합니다.

List<User> users = userLister.getUsers();  // This will actually work
                                           // without adding any line of code

훌륭합니다! 그렇지 않습니까?

  • UserLister인터페이스의 다른 구현을 사용하려면 어떻게해야 합니까? XML 만 변경하면됩니다.
  • UserLister구현이 준비 되지 않은 경우 어떻게 합니까? 시간 모의 구현을 프로그래밍 UserLister하고 뷰 개발을 용이하게합니다.
  • 더 이상 Spring을 사용하지 않으려면 어떻게합니까? 그냥 사용하지 마세요! 귀하의 응용 프로그램은 여기에 연결되어 있지 않습니다. Inversion of Control 은 "프레임 워크가 애플리케이션을 제어하는 ​​것이 아니라 애플리케이션이 프레임 워크를 제어합니다"라고 말합니다.

거기에 의존성 주입에 대한 다른 옵션이 있습니다. 제 생각에 Spring을 단순성, 우아함 및 안정성 외에도 유명하게 만든 것은 SpringSource의 사람들이 Spring을 다른 많은 공통 프레임 워크와 통합하는 데 도움이되는 많은 POJO를 프로그래밍했다는 것입니다. 응용 프로그램에 침입합니다. 또한 Spring에는 Spring MVC, Spring WebFlow, Spring Security와 같은 몇 가지 좋은 하위 프로젝트가 있으며 다시 한 번 기타 목록이 있습니다.

도움이 되었기를 바랍니다. 어쨌든, 나는 그가 나보다 더 잘하기 때문에 의존성 주입과 제어의 반전에 관한 Martin Fowler의 기사 를 읽는 것이 좋습니다. 기본 사항을 살펴 가지고 이해 한 후 봄 문서 , 내 의견으로는 되어 예전 사상 최고의 봄 책.


Spring 에는 MVC 프레임 워크 가 포함되어 있습니다 ( Skaffman이 올바르게 지적했듯이 ). 간단히 설명하기 위해 여기에 내 의견이 있습니다. Spring은 서비스 계층, 웹 계층 및 비즈니스 계층의 분리를 지원하지만 실제로 가장 잘하는 것은 객체의 "주입"입니다. 따라서 예를 들어 설명하려면 아래 예를 고려하십시오.

public interface FourWheel
{
   public void drive();
}

public class Sedan implements FourWheel
{
   public void drive()
   {
      //drive gracefully
   }
}

public class SUV implements FourWheel
{
   public void drive()
   {
      //Rule the rough terrain
   }
}

이제 코드에 다음과 같이 RoadTrip이라는 클래스가 있습니다.

public class RoadTrip
{
    private FourWheel myCarForTrip;
}

이제 Trip 인스턴스를 원할 때마다; 때로는 SUV로 FourWheel을 초기화하거나 때로는 Sedan을 원할 수 있습니다. 특정 상황에 따라 원하는 것이 실제로 다릅니다.

이 문제를 해결하려면 생성 패턴으로 팩토리 패턴을 갖고 싶을 것입니다. 공장이 올바른 인스턴스를 반환하는 곳. 따라서 결국에는 개체를 올바르게 인스턴스화하기 위해 많은 글루 코드가 생성됩니다. Spring은 글루 코드없이 글루 코드 작업을 가장 잘 수행합니다. XML로 매핑을 선언하면 개체가 자동으로 초기화됩니다. 또한 인스턴스에 싱글 톤 아키텍처를 많이 사용하며 최적화 된 메모리 사용에 도움이됩니다.

이를 Inversion Of Control이라고도합니다. 이를 수행하는 다른 프레임 워크는 Google guice, Pico 컨테이너 등입니다.

이 외에도 Spring은 유효성 검사 프레임 워크, JDBC, iBatis 및 Hibernate (및 더 많은)와 협력하여 DAO 계층에 대한 광범위한 지원을 제공합니다. 데이터베이스 트랜잭션에 대한 뛰어난 트랜잭션 제어를 제공합니다.

"Pro Spring"과 같은 좋은 책에서 읽을 수있는 Spring에는 더 많은 것이 있습니다.

다음 URL도 도움이 될 수 있습니다.
http://static.springframework.org/docs/Spring-MVC-step-by-step/
http://en.wikipedia.org/wiki/Spring_Framework
http://www.theserverside.com/tt/articles/article .tss? l = SpringFramework


예전에는 Spring 이 ( Guice , PicoContainer , ...) 와 같은 의존성 주입 프레임 작업 이었지만 이제는 Enterprise Application 을 구축하기위한 토털 솔루션이되었습니다 .

물론 스프링의 핵심 인 스프링 의존성 주입은 여전히 ​​존재하지만 (여기에서 다른 좋은 답변을 검토 할 수 있습니다), 스프링에서 더 많은 것이 있습니다.

Spring은 이제 많은 프로젝트를 가지고 있으며, 각각의 하위 프로젝트 ( http://spring.io/projects )가 있습니다. 어떤 사람이 봄에 대해 말할 때, 그가 말하는 봄 프로젝트무엇인지 , 봄 프레임 워크 로 알려진 스프링 코어 일 뿐인 지 아니면 다른 봄 프로젝트 인지 알아야 합니다.

너무 언급 할 가치가있는 일부 봄 프로젝트는 다음과 같습니다.

응용 프로그램에 대해 더 많은 특정 기능이 필요한 경우 여기에서도 찾을 수 있습니다.


  • 배치 애플리케이션 개발이 가능하도록 설계된 Spring Batch 배치 프레임 워크
  • Spring HATEOAS HATEOAS 주체에 REST API 기반을 쉽게 생성
  • 모바일 애플리케이션 개발을위한 Spring MobileSpring Andriod
  • Spring Shell 은 완전한 기능을 갖춘 셸 (일명 명령 줄) 애플리케이션을 빌드합니다.
  • 클라우드 애플리케이션을위한 Spring CloudSpring Cloud Data Flow

예를 들어 spring-social-facebook ( http://projects.spring.io/spring-social-facebook/ )과 같은 작은 프로젝트도 있습니다.

Spring Framework 프로젝트의 Spring MVC일부인 모듈을 가지고 있기 때문에 웹 개발에 Spring을 사용할 수 있습니다 . 또는 struts2 와 같은 다른 웹 프레임 작업과 함께 spring을 사용할 수 있습니다 .


봄은 무엇입니까? 곧 그 질문에 답하겠습니다. 먼저 victor hugo의 예를 다시 살펴 보겠습니다. 새로운 프레임 워크의 필요성을 정당화하지 못하기 때문에 좋은 예가 아닙니다.

public class BaseView {
  protected UserLister userLister;

  public BaseView() {
    userLister = new UserListerDB(); // only line of code that needs changing
  }
}

public class SomeView extends BaseView {
  public SomeView() {
    super();
  }

  public void render() {
    List<User> users = userLister.getUsers();
    view.render(users);
  }
}

끝난! 따라서 이제 수백 또는 수천 개의 뷰가 있더라도 Spring XML 접근 방식에서와 같이 코드 한 줄만 변경하면됩니다. 그러나 코드 줄을 변경하려면 XML을 편집하는 것과는 반대로 다시 컴파일해야합니까? 내 까다로운 친구, Ant와 스크립트를 사용하십시오!

그렇다면 Spring은 무엇입니까? 용도 :

  1. 무리를 따르는 맹인 개발자
  2. Employers who do not ever want to hire graduate programmers because they don't teach such frameworks at Uni
  3. Projects that started off with a bad design and need patchwork (as shown by victor hugo's example)

Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12


Very short summarized, I will say that Spring is the "glue" in your application. It's used to integrate different frameworks and your own code.


Spring is three things.

  1. Spring handles Dependency Injection and I recommend you read Martin Fowler's excellent introduction on dependency injection.
  2. The second thing Spring does is wrap excellent Java libraries in a very elegant way to use in your applications. For a good example see how Spring wraps Task Executors and Quartz Scheduler.
  3. Thirdly Spring provides a bunch of implementations of web stuff like REST, an MVC web framework and more. They figure since you are using Spring for the first two, maybe you can just use it for everything your web app needs.

The problem is that Spring DI is really well thought out, the wrappers around other things are really well thought out in that the other things thought everything out and Spring just nicely wraps it. The Spring implementations of MVC and REST and all the other stuff is not as well done (YMMV, IMHO) but there are exceptions (Spring Security is da bomb). So I tend to use Spring for DI, and its cool wrappers but prefer other stuff for Web (I like Tapestry a lot), REST (Jersey is really robust), etc.


What you'd probably want in a web application with Spring -

  • Spring MVC, which with 2.5+ allows you to use POJOs as Controller classes, meaning you don't have to extend from any particular framework (as in Struts or Spring pre-2.5). Controller classes are also dead simple to test thanks in part to dependency injection
  • Spring integration with Hibernate, which does a good job of simplifying work with that ORM solution (for most cases)
  • Using Spring for a web app enables you to use your Domain Objects at all levels of the application - the same classes that are mapped using Hibernate are the classes you use as "form beans." By nature, this will lead to a more robust domain model, in part because it's going to cut down on the number of classes.
  • Spring form tags make it easier to create forms without much hassle.

In addition, Spring is HUGE - so there are a lot of other things you might be interested in using in a web app such as Spring AOP or Spring Security. But the four things listed above describe the common components of Spring that are used in a web app.


I see two parts to this:

  1. "What exactly is Spring for" -> see the accepted answer by victor hugo.
  2. "[...] Spring is [a] good framework for web development" -> people saying this are talking about Spring MVC. Spring MVC is one of the many parts of Spring, and is a web framework making use of the general features of Spring, like dependency injection. It's a pretty generic framework in that it is very configurable: you can use different db layers (Hibernate, iBatis, plain JDBC), different view layers (JSP, Velocity, Freemarker...)

Note that you can perfectly well use Spring in a web application without using Spring MVC. I would say most Java web applications do this, while using other web frameworks like Wicket, Struts, Seam, ...


Spring is great for gluing instances of classes together. You know that your Hibernate classes are always going to need a datasource, Spring wires them together (and has an implementation of the datasource too).

Your data access objects will always need Hibernate access, Spring wires the Hibernate classes into your DAOs for you.

Additionally, Spring basically gives you solid configurations of a bunch of libraries, and in that, gives you guidance in what libs you should use.

Spring is really a great tool. (I wasn't talking about Spring MVC, just the base framework).


The accepted answer doesn't involve the annotations usage since Spring introduced support for various annotations for configuration.

Spring (Dependency Injection) approach

There the another way to wire the classes up alongside using a XML file: the annotations. Let's use the example from the accepted answer and register the bean directly on the class using one of the annotations @Component, @Service, @Repository or @Configuration:

@Component
public class UserListerDB implements UserLister {
    public List<User> getUsers() {
        // DB access code here
    }
}

This way when the view is created it magically will have a UserLister ready to work.

The above statement is valid with a little bonus of no need of any XML file usage and wiring with another annotation @Autowired that finds a relevant implementation and inject it in.

@Autowired
private UserLister userLister;

Use the @Bean annotation on a method used to get the bean implementation to inject.


The advantage is Dependency Injection (DI). It means outsourcing the task of object creation.Let me explain with an example.

public interface Lunch
{
   public void eat();
}

public class Buffet implements Lunch
{
   public void eat()
   {
      // Eat as much as you can 
   }
}

public class Plated implements Lunch
{
   public void eat()
   {
      // Eat a limited portion
   }
}

Now in my code I have a class LunchDecide as follows:

public class LunchDecide {
    private Lunch todaysLunch;
    public LunchDecide(){
        this.todaysLunch = new Buffet(); // choose Buffet -> eat as much as you want
        //this.todaysLunch = new Plated(); // choose Plated -> eat a limited portion 
    }
}

In the above class, depending on our mood, we pick Buffet() or Plated(). However this system is tightly coupled. Every time we need a different type of Object, we need to change the code. In this case, commenting out a line ! Imagine there are 50 different classes used by 50 different people. It would be a hell of a mess. In this case, we need to Decouple the system. Let's rewrite the LunchDecide class.

public class LunchDecide {
    private Lunch todaysLunch;
    public LunchDecide(Lunch todaysLunch){
        this.todaysLunch = todaysLunch
        }
    }

Notice that instead of creating an object using new keyword we passed the reference to an object of Lunch Type as a parameter to our constructor. Here, object creation is outsourced. This code can be wired either using Xml config file (legacy) or Java Annotations (modern). Either way, the decision on which Type of object would be created would be done there during runtime. An object would be injected by Xml into our code - Our Code is dependent on Xml for that job. Hence, Dependency Injection (DI). DI not only helps in making our system loosely coupled, it simplifies writing of Unit tests since it allows dependencies to be mocked. Last but not the least, DI streamlines Aspect Oriented Programming (AOP) which leads to further decoupling and increase of modularity. Also note that above DI is Constructor Injection. DI can be done by Setter Injection as well - same plain old setter method from encapsulation.


Spring is a good alternative to Enterprise JavaBeans (EJB) technology. It also has web framework and web services framework component.


  • Spring is a lightweight and flexible framework compare to J2EE.
  • Spring container act as a inversion of control.
  • Spring uses AOP i.e. proxies and Singleton, Factory and Template Method Design patterns.
  • Tiered architectures: Separation of concerns and Reusable layers and Easy maintenance.

여기에 이미지 설명 입력


Spring started off as a fairly simple dependency injection system. Now it is huge and has everything in it (except for the proverbial kitchen sink).

But fear not, it is quite modular so you can use just the pieces you want.

To see where it all began try:

http://www.amazon.com/Expert-One-Design-Development-Programmer/dp/0764543857/ref=sr_1_1?ie=UTF8&s=books&qid=1246374863&sr=1-1

It might be old but it is an excellent book.

For another good book this time exclusively devoted to Spring see:

http://www.amazon.com/Professional-Java-Development-Spring-Framework/dp/0764574833/ref=sr_1_2?ie=UTF8&s=books&qid=1246374863&sr=1-2

It also references older versions of Spring but is definitely worth looking at.


Spring was dependency injection in the begining, then add king of wrappers for almost everything (wrapper over JPA implementations etc).

Long story ... most parts of Spring preffer XML solutions (XML scripting engine ... brrrr), so for DI I use Guice

Good library, but with growing depnedenciec, for example Spring JDBC (maybe one Java jdbc solution with real names parameters) take from maven 4-5 next.

Using Spring MVC (part of "big spring") for web development ... it is "request based" framework, there is holy war "request vs component" ... up to You


Spring framework is defiantly good for web development more specific for Rest api. It because of it's dependency injection and integration with other modules like spring security, spring aop, mvc framework, microservices

Any application that you build definitely you need security.
If you are build a product, long maintenance, then you will defiantly need Aop concept.

If you application has much more load then you need to implement microservices.

Spring is giving all this thing in one platform. Support with many modules
Main thing is that spring is open source and extensible framework,have a hook everywhere to integrate custom code in life cycle.

Spring Data is one project which provide integration with your project.


So everything you need to build application has Spring.


In the past I thought about Spring framework from purely technical standpoint.

Given some experience of team work and developing enterprise Webapps - I would say that Spring is for faster development of applications (web applications) by decoupling its individual elements (beans). Faster development makes it so popular. Spring allows shifting responsibility of building (wiring up) the application onto the Spring framework. The Spring framework's dependency injection is responsible for connecting/ wiring up individual beans into a working application.

This way developers can be focused more on development of individual components (beans) as soon as interfaces between beans are defined.

Testing of such application is easy - the primary focus is given to individual beans. They can be easily decoupled and mocked, so unit-testing is fast and efficient.

Spring 프레임 워크는 웹 목적을 위해 @Controller ( @Restcontroller ), @Repository , @Component 와 같은 여러 특수 빈을 정의 합니다. Maven과 함께 Spring은 개발자에게 직관적 인 구조를 제공합니다. 개별 요소가 분리되어 재사용 될 수 있으므로 팀 작업이 쉽고 빠릅니다.

참고 URL : https://stackoverflow.com/questions/1061717/what-exactly-is-spring-framework-for

반응형