How to inject value into bean properties in Spring

In Spring, there are three ways to inject value into bean properties.

  • Normal way
  • Shortcut
  • “p” schema

See a simple Java class, which contains two properties – name and type. Later you will use Spring to inject value into the bean properties.

package com.mkyong.common;
public class FileNameGenerator { 
    private String name; 
    private String type; 
    public String getName() { 
        return name; 
    } 
    public void setName(String name) { 
        this.name = name; 
    } 
    public String getType() { 
        return type; 
    } 
    public void setType(String type) {  
        this.type = type; 
    }
}

1. Normal way

Inject value within a ‘value’ tag and enclosed with ‘property’ tag.



    
        
            mkyong
        
        
            txt
        
    

2. Shortcut

Inject value with “value” attribute.



    
        
        
    

3. “p” schema

Inject value by using “p” schema as an attributes.



    

Remember declares the xmlns:p=”http://www.springframework.org/schema/p in the Spring XML bean configuration file.

Conclusion

Which methods to use is totally base on personal preference, it will not affect the value inject into the bean properties.

你可能感兴趣的:(How to inject value into bean properties in Spring)