Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.
For the best experience please use the latest Chrome, Safari or Firefox browser.
Beans 
ApplicationContext.Beans 
//Soit la classe suivante que l'on faire gérer par Spring
public class BeanExemple{
private String msg;
private String nom;
public void getNom(){return nom;}
public void setNom(String n){nom = n;}
public BeanExemple(String m){msg=m;}
public void init() {}
public void cleanup() {}
}<!-- applicationContext.xml -->
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "..." ... >
<bean name="beanExemple" class="com.ipiecoles.BeanExemple"
scope="prototype" init-method="init" destroy-method="cleanup">
<constructor-arg value = "Hello "/><!-- OU -->
<constructor-arg index = "0" value = "Hello "/><!-- OU -->
<constructor-arg type = "java.lang.String" value = "Hello "/>
<property name = "nom" value = "World"/>
</bean>
</beans>
@Configuration
public class SpringConfig {
@Bean(initMethod = "init", destroyMethod = "cleanup")
@Scope("prototype")
public BeanExemple beanExemple(){
BeanExemple be = new BeanExemple("Hello ");
be.setNom("World");
return be;
}
}
public class BeanExemple{
private AutreBeanEx autreBean;
public void getAutreBean(){ return autreBean; }
public void setAutreBean(String b){
autreBean = b;
}
}<!-- applicationContext.xml -->
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "..." ... >
<bean name="autreBean" class="com.ipiecoles.AutreBeanEx"/>
<bean name="beanExemple" class="com.ipiecoles.BeanExemple">
<property name="autreBean" ref="autreBean"/>
<bean/>
</beans>
@Configuration
public class SpringConfig {
@Bean
public BeanExemple beanExemple(){
BeanExemple b = new BeanExemple();
b.setAutreBean(autreBeanEx());
}
@Bean
public AutreBeanEx autreBeanEx(){
return new AutreBeanEx();
}
}
ApplicationContextApplicationContext pour qu'ils puissent être gérés par le conteneur.
package com.ipiecoles;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
//Configuration Java
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
//OU Configuration XML
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BeanExemple be = ctx.getBean(BeanExemple.class);
//be peut être utilisé dans ce main et les beans déclarés
//dans la configuration ont été intégrés dans le conteneur
}
}
//Annotation des beans à gérer par Spring avec @Component
//(seulement pour les singletons)
@Component
public class BeanExemple{
//Injection d'un bean avec @Autowired, l'injection se fait par
//type. Attention, si deux beans existent du même type,
//cette injection échouera !
@Autowired
private AutreBeanEx autreBean;
}
@Component
public class AutreBeanEx{
}@Configuration
//L'annotation @ComponentScan permet de dire à Spring
//de chercher les beans dans toutes les classes de ce
//ce package.
@ComponentScan(basePackages = "com.ipiecoles")
public class SpringConfig {
}
@Service, @Controller, @Repository sont des spécialisations de
@Component et permettent à ces beans particuliers d'être traités de manière optimale par Spring.
@Component
public class BeanExemple{
//Utiliser @Resource pour injecter explicitement par nom
@Resource(name = "autreBean1")
private AutreBeanEx autreBean1;
//Ici @Autowired fonctionne car @Primary a été mis
//sur le bean principal
@Autowired
private AutreBeanEx autreBean;
}
public class AutreBeanEx{
private String nom;
private AutreBeanEx(String n){nom = n;}
}@Configuration
@ComponentScan(basePackages = "com.ipiecoles")
public class SpringConfig {
@Bean(name = "autreBean1")
public AutreBeanEx autreBean1(){
return new AutreBeanEx("Hello");
}
@Bean(name = "autreBean")
//L'annotation @Primary permet de lever le doute
//lorsque plusieurs beans ont le même type.
@Primary
public AutreBeanEx autreBean(){
return new AutreBeanEx("World");
}
}
@Qualifier peut être utilisé pour mettre des sortes de tags sur les beans afin de rendre plus souple l'injection automatique.
public class AutreBeanEx{
@PostConstruct //remplace init-method
public void init() {
// Instructions à exécuter après l'instanciation
}
@PreDestroy //remplace destroy-method
public void cleanup() {
// Instructions à exécuter avant la destruction
}
}@Configuration
public class SpringConfig {
@Bean
@Scope("prototype")
public AutreBeanEx autreBean(){
return new AutreBeanEx();
}
}
.properties.properties comme nous l'avons vu dans des cours précédents. Vous pouvez récupérer ces propriétés qui sont stockées dans le conteneur Spring, soit comme paramètres de construction de beans, ou directement dans votre application.
#app.properties
ipi.nom=IPI
ipi.message=Hello
<beans>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:app.properties"/>
</bean>
<!-- OU -->
<context:property-placeholder location="classpath:app.properties"/>
<bean id="beanExemple" class="com.ipiecoles.BeanExemple">
<property name="nom" value="${ipi.nom}"/>
<property name="message" value="${ipi.message}"/>
</bean>
</beans>
@Configuration
@PropertySource("classpath:app.properties")
public class SpringConfig {
@Value("${ipi.nom}")
private String nom;
@Value("${ipi.message}")
private String message;
@Bean(name = "beanExemple")
public BeanExemple beanExemple(){
return new
BeanExemple(message, nom);
}
}
application.properties (comme par exemple l'URL de connexion à la BDD), Spring récupère automatiquement ces valeurs pour paramétrer la création des beans nécessaires (à la connexion à la base de données par exemple).

.properties ou YAML).maven et Gradle. Exemple avec Maven :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.ipiecoles.java</groupId>
<artifactId>java240</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>java240</name>
<description>TP sur Spring</description>
<dependencies>
<!-- Ajout de dépendances starter en fonction des besoins-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Dépendance à MySQL => désactivation de la BDD intégrée et configuration optimisée pour MySQL-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Autres dépendances déclarées de manière classique-->
</dependencies>
</project>
package com.example.myapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//équivalent à @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
ApplicationContext à créer en fonction des dépendances présentes. Si Spring MVC (dépendance spring-boot-starter-web) ou Spring WebFlux (dépendance spring-boot-starter-webflux) est présent, l'ApplicationContext créé sera celui spécialisé pour les applications Web :
FreeMarker, Groovy, Thymeleaf ou Mustache (si dépendance présente). A noter que Spring Boot déconseille l'utilisation des JSP...CommandLineRunner.
import org.springframework.boot.*;
import org.springframework.stereotype.*;
@Component
public class MyBean implements CommandLineRunner {
@Autowired
private BeanExemple beanExample;
public void run(String... args) {
// Point d'entrée de votre application en ligne de commande.
}
}
run ce que vous auriez mis dans votre méthode main. Cela est nécessaire car la méthode main étant statique, on ne peut réaliser d'injection à l'intérieur.