深入Spring专题(15)

50 阅读2分钟

这是我参与2022首次更文挑战的第21天,活动详情查看2022首次更文挑战

除了这些属性,InjectSimple类定义了main()方法,该方法首先创建了ApplicaitonContext,从Spring中检索InjectSimple Bean,最后将这个Bean的属性值写入控制台输出,InjectSimple Bean的app-context-xml.xml中所包含的配置:

<beans ...>
	<bean id="injectSimpleConfig" class="com.ozx.InjectSimpleConfig"></bean>
    <bean id="injectSimple" class="com.ozx.InjectSimple" p:name="Tom" p:age="18" p:height="1.82" p:programmer="false" p:ageInSeconds="20220208"></bean>
</beans>

在bean上定义接收String值、原始值或原始包装器值的属性,然后通过使用标记为这些属性注入值,运行代码输出如下结果:

Name: Tom
Age: 18
Age in Seconds:20220208
Height:1.82
Is Programmer?: false

对于注解式简单值注入,可使用@Value注解应用于bean属性,这将注解应用于属性声明语句而不是setter方法。

public class InjectSimple{
    @Value("Tom")
    private String name;
    @Value("18")
    private int age;
    @Value("1.82")
    private float height;
    @Value("false")
    private boolean programmer;
    @Value("20220208")
    private Long ageInSeconds;
    public static void main(String... args){
        GenericXmlApplicationContext ctx=new GenericXmlApplicationContext();
        ctx.load("classpath:spring/app-context-xml.xml");
        ctx.refresh();
        
        InjectSimple injectSimple=ctx.getBean("injectSimple");
        System.out.println(injectSimple);
        ctx.close();
    }
    
    public void setAgeInSeconds(Long ageInSeconds){
        this.ageInSeconds=ageInSeconds;
    }
    
    public void setProgrammer(boolean programmer){
		this.programmer=programmer;
    }
    public void setAge(int age){
        this.age=age;
    }
    public void setHeight(float height){
        this.height=height;
    }
    public void setName(String name){
        this.name=name;
    }
    public String toString(){
        return "Name:"+name+"\n"+
            	"Age:"+age+"\n"+
            	"Age in Seconds:"+ageInSeconds+"\n“+
            	"Height:"+height+"\n"+
            	"Is Programmer?:"+programmer;
    }
}

Bean命名

Spring遵循一个简单的解析过程来确定bean使用的名称,如果为标记赋予一个id属性,那么该属性的值用作名称,如果没有指定id属性,Spring会查找name属性,如果定义了name属性,那么使用name属性中定义的第一个名称,如果既没有指定id属性,也没有指定name属性,那Spring使用该bean的类名作为名称,前提是没有其他bean使用相同的类名。如果声明了多个没有ID或名称的相同类型的bean,Spring在ApplicationContext初始化期间,在注入时抛出异常org.springframework.beans.factory.NotSuchBeanDefinitionException。