go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  Way#2 Fulfill the dependency need for another bean from the IoC container
 
Subject: Way#2 Fulfill the dependency need for another bean from the IoC container
Author: WebSpider
In response to: Way#1 Retrieve bean from the IoC Container by application
Posted on: 10/21/2019 05:45:47 AM

package com.example.spring.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Employee {
 
    private int id;
 
    @Autowired 
    private Name_XML_Bean           name;   
    
    @Autowired
    private Address_Configure_Bean  address;

    @Autowired
    private Sex_Annotation_Bean     sex;
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
    
    public void setName(String name) {
    	this.name.setName(name);
    }
        
    public void setAddress(String address) {
    	this.address.setAddress(address);
    }
    
    public void setSex(String sex) {
    	this.sex.setSex(sex);
    }
    
    @Override
    public String toString() {
        return "Employee [id=" + id + 
        		", name=" + name.getName() + 
        		", address=" + address.getAddress() + 
        		", sex=" + sex.getSex() + 
        		"]";
    }
 
}


Note:
  • There are three ways to do dependency injection (DI) via @Autowired: constructor/setter/field -- here @Autowired field is used.
  • Usually Name_XML_Bean, Address_Configure_Bean and Sex_Annotation_Bean are interfaces without knowing the concrete implementation until run-time.
  • The owner (this class -- Employee) must be a bean (@Component, @Controller, @Service or @Repository) inside IoC Container as well; otherwise the DI via @Autowired is doing nothing.

     

    > On 10/21/2019 05:40:51 AM WebSpider wrote:

    First, the IoC Container context should be generated via the corresponding configuration:
  • For XML configuration based bean -- context = new ClassPathXmlApplicationContext("app-config.xml");
  • For Java configuration based bean -- context = new AnnotationConfigApplicationContext(BeanConfig.class);
  • For annotation based bean -- context = new FileSystemXmlApplicationContext("/path/app-config.xml");


    Secondly, retrieve bean from the IoC Container via the context
    	Name_XML_Bean bean = context.getBean(Name_XML_Bean.class); 	
    






    References:

  •  


     
    Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
     
    Get your own forum today. It's easy and free.