Spring Framework est un framework d'application open source et d'inversion de conteneur de contrôle pour la plate-forme Java.
Version | Date de sortie |
---|---|
4.3.x | 2016-06-10 |
4.2.x | 2015-07-31 |
4.1.x | 2014-09-14 |
4.0.x | 2013-12-12 |
3.2.x | 2012-12-13 |
3.1.x | 2011-12-13 |
3.0.x | 2009-12-17 |
2.5.x | 2007-12-25 |
2.0.x | 2006-10-04 |
1.2.x | 2005-05-13 |
1.1.x | 2004-09-05 |
1.0.x | 2003-03-24 |
Étapes pour créer Hello Spring:
Employee.java
beans.xml
Customer.java
Employee.java
:
package com.test;
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayName() {
System.out.println(name);
}
}
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-4.3.xsd">
<bean id="employee" class="com.test.Employee">
<property name="name" value="test spring"></property>
</bean>
</beans>
Customer.java
:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Customer {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Employee obj = (Employee) context.getBean("employee");
obj.displayName();
}
}
Voici un exemple d'exécution autonome incluant / showcasing: dépendances minimales requises, configuration Java, déclaration Bean par annotation et configuration Java, injection de dépendance par constructeur et par propriété, et hooks Pre / Post .
Ces dépendances sont nécessaires dans le classpath:
À partir de la fin, il s'agit de notre classe principale qui sert d'espace réservé pour la méthode main()
qui initialise le contexte d'application en pointant sur la classe Configuration et charge tous les différents beans nécessaires pour présenter des fonctionnalités particulières.
package com.stackoverflow.documentation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
//initializing the Application Context once per application.
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(AppConfig.class);
//bean registered by annotation
BeanDeclaredByAnnotation beanDeclaredByAnnotation =
applicationContext.getBean(BeanDeclaredByAnnotation.class);
beanDeclaredByAnnotation.sayHello();
//bean registered by Java configuration file
BeanDeclaredInAppConfig beanDeclaredInAppConfig =
applicationContext.getBean(BeanDeclaredInAppConfig.class);
beanDeclaredInAppConfig.sayHello();
//showcasing constructor injection
BeanConstructorInjection beanConstructorInjection =
applicationContext.getBean(BeanConstructorInjection.class);
beanConstructorInjection.sayHello();
//showcasing property injection
BeanPropertyInjection beanPropertyInjection =
applicationContext.getBean(BeanPropertyInjection.class);
beanPropertyInjection.sayHello();
//showcasing PreConstruct / PostDestroy hooks
BeanPostConstructPreDestroy beanPostConstructPreDestroy =
applicationContext.getBean(BeanPostConstructPreDestroy.class);
beanPostConstructPreDestroy.sayHello();
}
}
La classe de configuration est annotée par @Configuration
et est utilisée comme paramètre dans le contexte d'application initialisé. L'annotation @ComponentScan
au niveau de la classe de la classe de configuration pointe vers un package à analyser pour les beans et les dépendances enregistrés à l'aide d'annotations. Enfin, l'annotation @Bean
sert de définition de bean dans la classe de configuration.
package com.stackoverflow.documentation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.stackoverflow.documentation")
public class AppConfig {
@Bean
public BeanDeclaredInAppConfig beanDeclaredInAppConfig() {
return new BeanDeclaredInAppConfig();
}
}
L'annotation @Component
sert à délimiter le POJO en tant que bean Spring disponible pour l'enregistrement lors de l'analyse des composants.
@Component
public class BeanDeclaredByAnnotation {
public void sayHello() {
System.out.println("Hello, World from BeanDeclaredByAnnotation !");
}
}
Notez que nous n'avons pas besoin d'annoter ou de marquer notre POJO, car la déclaration / définition du bean se produit dans le fichier de classe Configuration de l'application.
public class BeanDeclaredInAppConfig {
public void sayHello() {
System.out.println("Hello, World from BeanDeclaredInAppConfig !");
}
}
Notez que l'annotation @Autowired
est définie au niveau du constructeur. Notez également que, sauf définition explicite par nom, le démarrage automatique par défaut se produit en fonction du type du bean (dans cet exemple, BeanToBeInjected
).
package com.stackoverflow.documentation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BeanConstructorInjection {
private BeanToBeInjected dependency;
@Autowired
public BeanConstructorInjection(BeanToBeInjected dependency) {
this.dependency = dependency;
}
public void sayHello() {
System.out.print("Hello, World from BeanConstructorInjection with dependency: ");
dependency.sayHello();
}
}
Notez que l'annotation @Autowired
délimite la méthode setter dont le nom suit le standard JavaBeans.
package com.stackoverflow.documentation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BeanPropertyInjection {
private BeanToBeInjected dependency;
@Autowired
public void setBeanToBeInjected(BeanToBeInjected beanToBeInjected) {
this.dependency = beanToBeInjected;
}
public void sayHello() {
System.out.println("Hello, World from BeanPropertyInjection !");
}
}
Nous pouvons intercepter l’initialisation et la destruction d’un bean par les @PostConstruct
et @PreDestroy
.
package com.stackoverflow.documentation;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class BeanPostConstructPreDestroy {
@PostConstruct
public void pre() {
System.out.println("BeanPostConstructPreDestroy - PostConstruct");
}
public void sayHello() {
System.out.println(" Hello World, BeanPostConstructPreDestroy !");
}
@PreDestroy
public void post() {
System.out.println("BeanPostConstructPreDestroy - PreDestroy");
}
}
Spring est un framework qui fournit un tas de classes. En utilisant ceci, nous n'avons pas besoin d'écrire la logique de la plaque chauffante dans notre code, donc Spring fournit une couche abstraite sur J2ee.
Par exemple, dans Simple JDBC Application, le programmeur est responsable de
Ce qui est traité comme un code standard comme chaque programmeur écrit le même code. Donc, pour simplifier, le cadre prend en charge la logique standard et le programmeur doit écrire uniquement la logique métier. Ainsi, en utilisant le framework Spring, nous pouvons développer rapidement des projets avec un minimum de lignes de code, sans aucun bogue, le coût de développement et le temps également réduit.
Strut est un cadre qui fournit une solution aux aspects Web uniquement et les structures sont invasives dans la nature. Le printemps a de nombreuses fonctionnalités par rapport aux jambes de force, nous devons donc choisir le printemps.
On peut donc enfin dire que Spring est une alternative aux Struts. Mais Spring ne remplace pas l'API J2EE, car les classes fournies par Spring utilisent en interne des classes d'API J2EE. Le printemps est un vaste cadre qui a été divisé en plusieurs modules. Aucun module n'est dépendant d'un autre, à l'exception de Spring Core. Certains modules importants sont