以beans的约束配置为例:
复制Scheme的路径:http://www.springframework.org/schema/beans/spring-beans.xsd进入Eclipse - -> Window --> preference --> XML Catalog界面 点击Add按钮,引入本地约束文件(Spring解压包下) 点击OK完成在XML文件中有关Bean的提示设置。bean标签的 id 和 name 属性都能够标识这个标签,但是两者在使用上存在着差别:
id :使用了约束中的的唯一约束,里面不能出现特殊字符name :未使用约束中的的唯一约束(理论上可以重复,但实际开发不允许重复),里面可以出现特殊字符下图介绍了传统的三种方式为类中的属性注入值,Spring底层采用构造方法和Set()方法的方式为属性注入值:
构造方法的方式属性注入 xml文件信息: <!-- Spring属性注入 --> <!-- 1.构造方法方式 --> <bean id="car" class="com.ahoo.spring.demo2.Car"> <constructor-arg name="name" value="mini Cooper" /> <constructor-arg name="price" value="480000" /> </bean> 测试类: @Test /** * 构造方法方式的属性注入 */ public void demo1() { //创建Spring工厂 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Car car = (Car) applicationContext.getBean("car"); System.out.println(car); } set()方法的方式属性注入 <!-- 2.set方法方式 --> <bean id="car2" class="com.ahoo.spring.demo2.Car2"> <property name="name" value="奔驰" /> <property name="price" value="1000000" /> </bean> <!-- 2.set方法方式注入对象的属性 --> <bean id="emploee" class="com.ahoo.spring.demo2.Emploee"> <property name="name" value="Ahoo" /> <property name="car" ref="car" /> </bean> 测试类: @Test /** * set方法方式的属性注入 */ public void demo2() { //创建Spring工厂 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Car2 car2 = (Car2) applicationContext.getBean("car2"); System.out.println(car2); } @Test /** * set方法方式的属性注入引用类型的属性 */ public void demo3() { //创建Spring工厂 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Emploee emploee = (Emploee) applicationContext.getBean("emploee"); System.out.println(emploee); }SpEL:Spring Expression Language ,Spring表达式语。在Spring3.0及以上版本引入表达式语言来完成属性注入:
<bean id="carinfo" class="com.ahoo.spring.demo2.CarInfo"></bean> <!-- SpEl方式注入 --> <bean id="car2" class="com.ahoo.spring.demo2.Car2"> <property name="name" value=#{carinfo.name} /> <property name="price" value=#{carinfo.calculator()} /> </bean>