IT

Xml 구성 및 주석 기반 구성

lottoking 2020. 7. 1. 07:42
반응형

Xml 구성 및 주석 기반 구성 [닫기]


최근에 작업하고있는 몇 가지 큰 프로젝트에서 하나 또는 다른 것을 선택하는 것이 점점 중요 해지는 것처럼 보입니다 (XML 또는 Annotation). 프로젝트가 성장함에 따라 일관성은 유지 관리에 매우 중요합니다.

내 질문은 Annotation 기반 구성에 비해 XML 기반 구성의 장점은 무엇이며 XML 기반 구성에 비해 Annotation 기반 구성의 장점은 무엇입니까?


주석은 그 용도가 있지만 XML 구성을 죽이는 가장 중요한 요소는 아닙니다. 나는 두 가지를 혼합하는 것이 좋습니다!

예를 들어 Spring을 사용한다면 애플리케이션의 의존성 주입 부분에 XML을 사용하는 것이 전적으로 직관적입니다. 이것은 의존성을 필요로하는 코드에 어떤 종류의 주석을 사용하면 코드 가이 자동 구성을 인식하게하는 반면 코드를 사용하는 코드에서 코드의 의존성을 얻습니다.

그러나 트랜잭션 관리에 XML을 사용하는 대신 메서드를 주석이있는 트랜잭션으로 표시하는 것은 프로그래머가 알고 싶어하는 정보이기 때문에 완벽한 의미가 있습니다. 그러나 SubtypeX 대신 SubtypeY로 인터페이스가 주입 될 것입니다 .SubtypeX를 주입하려면 코드를 변경해야하지만 인터페이스 계약이 있기 때문에 클래스를 포함하지 않아야합니다. XML을 사용하면 XML 매핑을 변경하기 만하면되므로 매우 빠르고 어려움이 없습니다.

나는 JPA 주석을 사용하지 않았으므로 얼마나 잘하는지 모르겠지만 XML로 데이터베이스에 Bean의 매핑을 유지하는 것이 좋습니다. 객체는 정보의 출처를 신경 쓰지 않아야하므로 정보로 할 수있는 일만 신경 써야합니다. 그러나 당신이 JPA를 좋아한다면 (나는 그것에 대한 경험이 없다), 그것을 위해 가십시오.

일반적으로 : 주석이 기능을 제공하고 그 자체로 주석 역할을하고이 주석없이 정상적으로 기능하기 위해 코드를 특정 프로세스에 연결하지 않으면 주석으로 이동합니다. 예를 들어, 트랜잭션으로 표시된 트랜잭션 메소드는 운영 로직을 종료하지 않으며 코드 레벨 주석으로도 사용됩니다. 그렇지 않으면이 정보가 XML로 표현되는 것이 가장 좋습니다. 결국 코드의 작동 방식에 영향을 주지만 코드의 주요 기능은 변경되지 않으므로 소스 파일에 속하지 않기 때문입니다.


여기에는 외부화 된 메타 데이터와 인라인 메타 데이터의 문제가 더 광범위합니다. 객체 모델이 한 가지 방식으로 만 지속되는 경우 인라인 메타 데이터 (예 : 주석)가 더 간결하고 읽기 쉽습니다.

그러나 각 응용 프로그램이 다른 방식으로 모델을 유지하려는 방식으로 개체 모델을 다른 응용 프로그램에서 재사용 한 경우 메타 데이터 (예 : XML 설명자)를 외부화하는 것이 더 적합 해집니다.

주석이 더 멋지지만 둘 중 어느 것도 좋지 않으므로 둘 다 지원됩니다. 결과적으로 JPA와 같은 새로운 헤어 온 프레임 워크는 더 강조되는 경향이 있습니다. 네이티브 Hibernate와 같은보다 성숙한 API는 둘 다를 제공합니다. 둘 중 어느 것도 충분하지 않기 때문입니다.


나는 항상 주석 이 클래스가 무엇을 할 수 있는지 또는 다른 클래스 어떻게 상호 작용 하는지에 대한 일종의 지표로 생각 합니다.

반면에 스프링 XML 구성은 그저 구성입니다.

예를 들어, 프록시의 IP 및 포트에 대한 정보는 XML 파일로 정의되며 런타임 구성입니다.

사용 @Autowire, @Element클래스와는 어떤 프레임 워크를 표시하는 것은 주석을 잘 사용하는 것입니다.

@Webservice주석에 URL을 넣는 것은 좋지 않습니다.

그러나 이것은 단지 내 의견입니다. 상호 작용과 구성 간의 경계가 항상 명확한 것은 아닙니다.


나는 몇 년 동안 Spring을 사용해 왔으며 필요한 XML의 양은 확실히 지루해졌습니다. Spring 2.5의 새로운 XML 스키마와 주석 지원 사이에서 나는 보통 다음과 같은 일을한다.

  1. "component-scan"을 사용하여 @Repository, @Service 또는 @Component를 사용하는 클래스를 자동로드하십시오. 나는 보통 모든 빈에 이름을 부여하고 @Resource를 사용하여 서로 연결한다. 이 배관은 자주 바뀌지 않으므로 주석이 의미가 있습니다.

  2. 모든 AOP에 "aop"네임 스페이스 사용 이것은 정말 잘 작동합니다. @Transactional을 모든 곳에 두는 것은 일종의 드래그이기 때문에 여전히 트랜잭션에도 사용합니다. 모든 서비스 또는 저장소에서 메소드에 대해 명명 된 포인트 컷을 작성하고 조언을 매우 빠르게 적용 할 수 있습니다.

  3. HibernateJpaVendorAdapter와 함께 LocalContainerEntityManagerFactoryBean을 사용하여 Hibernate를 구성합니다. 이를 통해 Hibernate는 클래스 경로에서 @Entity 클래스를 쉽게 자동 검색 할 수 있습니다. 그런 다음 LCEMFB를 참조하는 "factory-bean"및 "factory-method"를 사용하여 명명 된 SessionFactory Bean을 작성합니다.


주석 전용 접근 방식을 사용하는 데있어 중요한 부분은 "bean name"개념이 어느 정도 사라진다는 것입니다 (중요하지 않음).

Spring의 "bean names"는 구현 클래스에 대한 추가적인 추상화 수준을 형성합니다. XML을 사용하면 Bean 이름과 관련하여 정의되고 참조됩니다. 주석을 사용하면 클래스 / 인터페이스에서 참조됩니다. (빈 이름이 존재하더라도 알 필요는 없습니다)

불필요한 추상화를 제거하면 시스템이 단순화되고 생산성이 향상된다고 확신합니다. 들어 대형 프로젝트 나는 XML을 제거하기로 이익이 상당 할 수 있다고 생각합니다.


XML 기반 접근 방식에서는 가시성이 큰 승리라고 생각합니다. XML 문서를 탐색하기위한 다양한 도구 (예 : Visual Studio + ReSharper의 파일 구조 창)를 고려할 때 XML이 그렇게 나쁘지 않다는 것을 알았습니다.

확실히 혼합 접근법을 취할 수는 있지만 프로젝트의 새로운 개발자가 다른 객체가 구성되거나 매핑되는 위치를 알아내는 것이 어려울 수 있기 때문에 위험합니다.

몰라요 결국 XML 지옥은 나에게 그렇게 나쁘게 보이지는 않습니다.


어노테이션으로 구성 할 수없는 일부 옵션이 있으므로 구성하려는 모든 항목에 따라 다릅니다. 주석 측면에서 보면 :

  • 더하기 : 주석이 덜 어색합니다.
  • 빼기 : 주석이 잘 보이지 않습니다

더 중요한 것은 당신에게 달려 있습니다 ...

일반적으로 한 가지 방법을 선택하고 닫힌 일부 제품에 사용하는 것이 좋습니다.

(예외 : XML 기반 구성을 선택하는 경우 @Autowire 주석을 사용하는 것이 좋습니다. 혼합 방식이지만 가독성과 유지 보수성 모두에 도움이됩니다)


리팩토링 및 다른 코드 변경과 비교할 다른 측면이 있습니다. XML을 사용하는 경우 모든 XML 컨텐츠를 처리해야하므로 리팩토링을 위해 많은 노력이 필요합니다. 그러나 주석을 사용할 때는 쉽습니다.

내가 선호하는 방법은 주석이없는 (또는 최소한의) 주석 기반 Java 기반 구성입니다. http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java


I might be wrong, but I thought Annotations (as in Java's @Tag and C#'s [Attribute]) were a compile-time option, and XML was a run-time option. That to me says the are not equivalent and have different pros and cons.


I also think a mix is the best thing, but it also depends on the type of configuration parameters. I'm working on a Seam project which also uses Spring and I usually deploy it to different development and test servers. So I have split:

  • Server specific configuration (Like absolute paths to resources on server): Spring XML file
  • Injecting beans as members of other beans (or reusing a Spring XML defined value in many beans): Annotations

The key difference is that you don't have to recompile the code for all changing server-specific configurations, just edit the xml file. There's also the advantage that some configuration changes can be done by team members who don't understand all the code involved.


In the scope of DI container, I consider annotation based DI is abusing the use of Java annotation. By saying that, I don't recommend to use it widely in your project. If your project does really needs the power of DI container, I would recommend to use Spring IoC with Xml based configuration option.

If it is just for a sake of Unit-test, developers should apply Dependency Inject pattern in their coding and take advantages from mocking tools such as EasyMock or JMock to circumvent dependencies.

You should try to avoid using DI container in its wrong context.


Configuration information that is always going to be linked to a specific Java component (class, method, or field) is a good candidate to be represented by annotations. Annotations work especially well in this case when the configuration is core to the purpose of the code. Because of the limitations on annotations, it's also best when each component can only ever have one configuration. If you need to deal with multiple configurations, especially ones that are conditional on anything outside the Java class containing an annotation, annotations may create more problems than they solve. Finally, annotations cannot be modified without recompiling the Java source code, so anything that needs to be reconfigurable at run time can't use annotations.

Please refer following links. They might be useful too.

  1. Annotations vs XML, advantages and disadvantages
  2. http://www.ibm.com/developerworks/library/j-cwt08025/

This is the classic 'Configuration versus Convention' question. Personal taste dictates the answer in most cases. However, personally I prefer Configuration (i.e. XML based) over Convention. IMO IDE's are sufficiently robust enough to overcome some of the XML hell people often associate w/ the building and maintaining an XML based approach. In the end, I find the benefits of Configuration (such as building utilities to build, maintain and deploy the XML config file) outweighs Convention in the long run.


I use both. Mostly XML, but when I have a bunch of beans that inherit from a common class and have common properties, I use annotations for those, in the superclass, so I don't have to set the same properties for each bean. Because I'm a bit of a control freak, I use @Resource(name="referredBean") instead of just autowiring stuff (and save myself a lot of trouble if I ever need another bean of the same class as the original referredBean).


There are some pros and cons of annotation configuration from my experience:

  • When it comes to JPA configuration since it is done once and usually are not changed quite often I prefer to stick to annotation configuration. There maybe a concern regarding possibility to see a bigger picture of configuration - in this case I use MSQLWorkbench diagrams.
  • Xml configuration is very good to get a bigger picture of application but it maybe cumbersome to find some errors until runtime. In this case Spring @Configuration annotation sounds as a better choice since it let you see a bigger picture as well and also allows to validate configuration on compile time.
  • As for Spring configuration I prefer to combine both approaches: use @Configuration annotation with Services and Query interfaces and xml configuration for dataSource and spring configuration stuff like context:component-scan base-package="..."
  • But xml configuration bits java annotations when it comes to flow configuration(Spring Web Flow or Lexaden Web Flow) since it is extremely important to see a bigger picture of the whole business process. And it sounds cumbersome to have it implemented with annotations approach.

I prefer combining both approaches - java annotations and essential xml minimum that minimize configuration hell.


For Spring Framework I like the idea of being able to use the @Component annotation and setting the "component-scan" option so that Spring can find my java beans so that I do not have to define all of my beans in XML, nor in JavaConfig. For example, for stateless singleton java beans that simply need to be wired up to other classes (via an interface ideally) this approach works very well. In general, for Spring beans I have for the most part moved away from Spring XML DSL for defining beans, and now favor the use of JavaConfig and Spring Annotations because you get some compile time checking of your configuration and some refactoring support that you don't get with Spring XML configuration. I do mix the two in certain rare cases where I've found that JavaConfig/Annotations can't do what is available using XML configuration.

For Hibernate ORM (haven't used JPA yet) I still prefer the XML mapping files because annotations in domain model classes to some degree violates The Clean Architecture which is a layering architectural style I have adopted over the past few years. The violation occurs because it requires the Core Layer to depend on persistence related things such as Hibernate or JPA libraries and it makes the domain model POJOs a bit less persistence ignorant. In fact the Core Layer is not supposed to depend on any other infrastructure at all.

However, if The Clean Architecture is not your "cup of tea" then I can see there are definitely advantages (such as convenience and maintainability) of using Hibernate/JPA annotations in domain model classes over separate XML mapping files.

참고URL : https://stackoverflow.com/questions/182393/xml-configuration-versus-annotation-based-configuration

반응형