Milton Díaz
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Spring Boot Inyección de Dependencias La inyección de dependencias es un patrón de diseño utilizado para gestionar las relaciones entre objetos de manera más flexible y desacoplada. Permite que los objetos reciban sus dependencias desde una fuente externa en lugar de crearlas por sí mismos, lo que mejora la modularidad y facilita las pruebas. Spring Boot aprovecha fuertemente la programación orientada a interfaces como una buena práctica de diseño, especialmente en la inyección de dependencias, donde los objetos no se instancian explícitamente. En su lugar, el contenedor de Spring (IoC container) se encarga de crear e inyectar las dependencias necesarias. La inyección de dependencias es una técnica que ayuda a construir aplicaciones más modulares, flexibles y fáciles de mantener, ya que las dependencias de un objeto sean gestionadas de forma externa. ## Dependencia Una dependencia es cualquier objeto que otra clase necesita para funcionar. Por ejemplo, una clase de servicio puede necesitar una instancia de un repositorio para acceder a los datos. ## Inyección La inyección consiste en proporcionar esas dependencias desde el exterior, en lugar de que la propia clase las cree. Esto se realiza mediante un contenedor o framework (como Spring), lo que promueve un diseño más desacoplado y fácil de mantener. ## Tipos de Inyección de Dependencias - Inyección por Atributo o Campo - Inyección por Constructor - Inyección por Setter # Beans Un bean en Spring es un objeto que es instanciado, configurado, ensamblado y gestionado por el contenedor de Spring. Los beans pueden ser configurados de varias formas, incluyendo anotaciones como @Component, @Service, @Repository y @Controller. También pueden ser configurados en archivos XML y configuración Java con clases anotadas con @Configuration. ## Configuración basada en XML ```java <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.xsd"> <bean id="myService" class="com.example.MyService"> <constructor-arg ref="myRepository"/> </bean> <bean id="myRepository" class="com.example.MyRepository"/> </beans> ``` ## Configuración basada en Java con clases anotadas con @Configuration ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(myRepository()); } @Bean public MyRepository myRepository() { return new MyRepository(); } } ``` Luego, en otra parte de la aplicación, podríamos inyectar ese bean: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MiControlador { @Autowired private MyService myService; public void ejecutar() { myService.procesar(); } } ``` ## Ciclo de Vida de un Bean Los beans tienen un ciclo de vida que puede incluir métodos de inicialización y destrucción, permitiendo a los desarrolladores ejecutar lógica específica en esos momentos. 1. Creación: El contenedor de Spring instancia el bean. 2. Inicialización: Se ejecutan los métodos de inicialización (@PostConstruct, métodos definidos en la configuración). 3. Uso: El bean está listo para ser utilizado por la aplicación. 4. Destrucción: Se ejecutan los métodos de destrucción (@PreDestroy, métodos definidos en la configuración) antes de que el bean sea destruido. ### Inicialización de un Bean usando @PostConstruct @PostConstruct se usa para definir un método que debe ejecutarse después de que el Bean haya sido completamente inicializado por el contenedor (por ejemplo, Spring). Este método se ejecuta después de que se inyecten todas las dependencias y se construya el Bean. También se puede utilizar el constructor para inicializar un Bean, pero con la diferencia de que el constructor se ejecutará antes de que se inyecten todas las dependencias del Bean. ```java import javax.annotation.PostConstruct; public class MyBean { @PostConstruct public void init() { System.out.println("Bean inicializado mediante @PostConstruct"); } } ``` ### Destrucción de un Bean usando @PreDestroy @PreDestroy se usa para definir un método que debe ejecutarse justo antes de que el Bean sea destruido por el contenedor. Este método es útil para liberar recursos, cerrar conexiones, etc. ```java import javax.annotation.PreDestroy; public class MyBean { @PreDestroy public void destroy() { System.out.println("Bean destruido mediante @PreDestroy"); } } ``` # @Autowired se utiliza para inyectar automáticamente las dependencias de un bean en otro bean. Es parte del soporte de inyección de dependencias de Spring y permite al framework resolver e inyectar automáticamente los componentes necesarios en los lugares apropiados. ### Ejemplo de Inyección por Atributo o Campo En el siguiente ejemplo el servicio `MyService` esta siendo inyectado por el repositorio `MyRepository`. ```java import org.springframework.stereotype.Component; @Component public class MyRepository { public void doSomething() { System.out.println("Doing something..."); } } ``` ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { @Autowired private MyRepository myRepository; public void someOperation() { myRepository.doSomething(); } } ``` ### Ejemplo de Inyección por Constructor ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { private MyRepository myRepository; public MyService(MyRepository myRepository) { this.myRepository = myRepository; } public void someOperation() { myRepository.doSomething(); } } ``` **Nota:** En la inyección de dependencias por constructor no es necesario especificar la anotación `@Autowired`, ya que por defecto Spring reconoce que se trata de una inyección. ### Ejemplo de Inyección por Setter ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { private MyRepository myRepository; @Autowired public void setMyRepository(MyRepository myRepository) { this.myRepository = myRepository; } public void someOperation() { myRepository.doSomething(); } } ``` **Nota:** Al utilizar la inyección por constructor o setter, el parámetro que se recibe es el bean gestionado por el contenedor de Spring. ## Inyección Mediante Interfaces Inyectar dependencias mediante interfaces es una práctica común y recomendada en la programación orientada a objetos y, especialmente, en el desarrollo de aplicaciones Spring. Supongamos que tenemos una interfaz `NotificationService` y dos implementaciones: `EmailNotificationService` y `SmsNotificationService`. ```java public interface NotificationService { void sendNotification(String message); } ``` ```java import org.springframework.stereotype.Service; @Service public class EmailNotificationService implements NotificationService { @Override public void sendNotification(String message) { System.out.println("Sending email with message: " + message); } } ``` ```java import org.springframework.stereotype.Service; @Service public class SmsNotificationService implements NotificationService { @Override public void sendNotification(String message) { System.out.println("Sending SMS with message: " + message); } } ``` Ahora en el controlador inyectaríamos la interfaz `NotificationService` mas no el servicio directamente. ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { private final NotificationService notificationService; @Autowired public UserController(NotificationService notificationService) { this.notificationService = notificationService; } public void someOperation() { notificationService.sendNotification(); } } ``` Sin embargo esto nos daría un error, ya que Sprig no sabría cual de los dos servicios inyectar, para ello, podemos hacer uso de las anotacion `@Primary` y `@Qualifier`. ## @Primary La anotación @Primary se usa para marcar un bean como la opción preferida cuando hay múltiples beans del mismo tipo disponibles. Si no se especifica explícitamente un bean con @Qualifier, Spring inyectará el bean marcado con @Primary. En este ejemplo, EmailNotificationService está marcado con @Primary. Si Spring encuentra múltiples beans del tipo NotificationService, inyectará PrimaryUserService por defecto. ```java import org.springframework.stereotype.Service; @Service @Primary public class EmailNotificationService implements NotificationService { @Override public void sendNotification(String message) { System.out.println("Sending email with message: " + message); } } ``` ## @Qualifier La anotación @Qualifier se utiliza para especificar cuál bean debe ser inyectado cuando hay múltiples beans del mismo tipo disponibles. Esto se hace proporcionando un nombre de calificador que coincide con el nombre del bean que se desea inyectar. En este ejemplo, UserController inyecta específicamente SmsNotificationService utilizando @Qualifier. ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { private final NotificationService notificationService; @Autowired public UserController(@Qualifier("smsNotificationService") NotificationService notificationService) { this.notificationService = notificationService; } public void someOperation() { notificationService.sendNotification(); } } ``` **Nota:** @Qualifier tiene prioridad sobre @Primary. Si se especifica @Qualifier, Spring inyectará el bean correspondiente al @Qualifier, ignorando el bean anotado con @Primary. # Scopes (contextos) En Spring, los scopes (contextos) determinan el ciclo de vida y la visibilidad de los beans dentro del contenedor. Hay varios tipos de contextos, pero los más comunes son Singleton, RequestScope y SessionScope. ## Singleton Scope Es el scope por defecto en Spring. En este contexto, el contenedor de Spring crea una única instancia del bean para todo el ciclo de vida de la aplicación. Características - Ciclo de vida: Toda la aplicación. - Visibilidad: Global dentro del contenedor de Spring. - Uso típico: Beans que contienen lógica sin estado (stateless) o que deben compartirse a lo largo de toda la aplicación. ## Request Scope En este contexto, Spring crea una nueva instancia del bean para cada solicitud HTTP. Se utiliza principalmente en APIs. Características - Ciclo de vida: Una solicitud HTTP. - Visibilidad: Dentro de la misma solicitud HTTP. - Uso típico: Beans que contienen lógica dependiente de una única solicitud HTTP. ## Session Scope En este contexto, Spring crea una nueva instancia del bean para cada sesión HTTP. Se utiliza principalmente en aplicaciones web. Características - Ciclo de vida: Una sesión HTTP. - Visibilidad: Dentro de la misma sesión HTTP. - Uso típico: Beans que deben mantener datos específicos de un usuario durante su sesión en la aplicación. # @Value se utiliza para inyectar valores en los campos de una clase desde el archivo de configuración (por ejemplo, application.properties o application.yml) o desde otros recursos como variables de entorno o valores predeterminados. Esta anotación es útil para inyectar valores constantes o configuraciones que no cambian durante la ejecución de la aplicación. Por ejemplo, en application.properties: ```java my.property.value=Hello, Spring! ``` Luego, en alguna clase de nuestro proyecto, podemos utilizarla con la anotación @Value para inyectar este valor: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyComponent { @Value("${my.property.value}") private String myValue; public void printValue() { System.out.println(myValue); } } ``` # Archivo de propiedades de la aplicación El archivo de propiedades de la aplicación **(application.properties o application.yml)** en Spring Boot es un archivo de configuración ubicado en `src/main/resources`, que permite definir valores externos al código fuente para personalizar el comportamiento de la aplicación. Se utiliza para configurar propiedades como el puerto del servidor, los datos de conexión a bases de datos, parámetros personalizados, perfiles de entorno, entre otros. Además, como se vio anteriormente, facilita la inyección de valores en clases mediante anotaciones como @Value o @ConfigurationProperties, lo que hace que la aplicación sea más flexible, mantenible y adaptable a distintos entornos sin necesidad de recompilar. # Referencias circulares Las referencias circulares ocurren cuando dos o más *beans* se dependen mutuamente entre sí, creando un ciclo que impide que el contenedor de Spring los inicialice correctamente. Ejemplo ```java @Service public class ServicioA { private final ServicioB servicioB; @Autowired public ServicioA(@Lazy ServicioB servicioB) { this.servicioB = servicioB; } } @Service public class ServicioB { private final ServicioA servicioA; @Autowired public ServicioB(ServicioA servicioA) { this.servicioA = servicioA; } } ``` Aquí, Spring no puede crear ServicioA sin ServicioB, ni ServicioB sin ServicioA, y eso genera un error de referencia circular. En Spring 6 y Spring Boot 3 (y versiones recientes), por defecto se lanza un error como este: `The dependencies of some of the beans in the application context form a cycle...` **¿Cómo se soluciona?** - Reestructurando el diseño **(es lo ideal)**: evita que los beans se dependan mutuamente. “Deberíamos intentar rediseñar los componentes correctamente para que su jerarquía esté bien diseñada y no se necesiten dependencias circulares.” (Hombergs T, 2024) - Usando `@Lazy` en una de las dependencias: esto retrasa la creación de uno de los beans, rompiendo el ciclo: ```java @Component public class ServicioA { @Autowired @Lazy private ServicioB servicioB; } ``` - Constructor vs Setter Injection: a veces, usar inyección por setter en lugar de constructor puede ayudar con la carga diferida. - Evitar lógica fuerte en constructores: deja la lógica pesada para métodos @PostConstruct o inicialización posterior. Para mas información [Dependencias circulares en Spring](https://www.baeldung.com/circular-dependencies-in-spring) # Bibliografía Guzmán, A. (s. f.). *Spring Framework 6 & Spring Boot 3 desde cero a experto.* Udemy. https://www.udemy.com/course/spring-framework-5 Hombergs, T. (2024, mayo 11). *Dependencias circulares en Spring.* Baeldung. https://www.baeldung.com/circular-dependencies-in-spring

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully