除了普通属性、对象属性(Bean)、集合等属性外,Spring 也能够将其他类型的属性注入到 Bean 中,例如 Null 值、字面量、复合物属性等。
注入 Null 值
我们可以在 XML 配置文件中,通过 元素将 Null 值注入到 Bean 中。
下面,我们通过一个简单的实例,来演示下如何将 Null 值注入到 Bean 中。
1. 参考《第一个 Spring 程序》,新建一个名为 my-spring-demo5 的 Java 项目。
2. 在 net.biancheng.c 包中,创建一个名为 ExampleBean 的类,代码如下。
1. package net.biancheng.c; 3. public class ExampleBean { 4. private String propertyNull; 6. public void setPropertyNull(String propertyNull) { 7. this.propertyNull = propertyNull; 8. } 10. @Override 11. public String toString() { 12. return "ExampleBean{" + 13. "propertyNull='" + propertyNull + '\'' + 14. '}'; 15. } 16. }
3. 在 src 目录下创建 Spring 配置文件 Beans.xml,配置如下。
1.
4. 在 net.biancheng.c 包下,创建一个名为 MainApp 的类,代码如下。
1. package net.biancheng.c;
3. import org.apache.commons.logging.Log;
4. import org.apache.commons.logging.LogFactory;
5. import org.springframework.context.ApplicationContext;
6. import org.springframework.context.support.ClassPathXmlApplicationContext;
8. public class MainApp {
9. private static final Log LOGGER = LogFactory.getLog(MainApp.class);
11. public static void main(String[] args) {
12. //获取 ApplicationContext 容器
13. ApplicationContext context = new ClassPathXmlApplicationContext("B