Spring xml

A(1)最基本部分

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 </beans>

(2)p跟c的配置

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

p跟c的配置都需要分别导入以上两个才能够使用

P可以直接注入属性的值

C听过构造体注入

(3)注解配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:aop="http://www.springframework.org/schema/aop"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans.xsd
 8        http://www.springframework.org/schema/context
 9        http://www.springframework.org/schema/context/spring-context.xsd
10        http://www.springframework.org/schema/aop
11        http://www.springframework.org/schema/aop/spring-aop.xsd">
12     <context:annotation-config/>
13     <bean id="cat" class="com.ma.pojo.Cat"></bean>
14     <bean id="dog" class="com.ma.pojo.Dog"></bean>
15     <bean id="dog11" class="com.ma.pojo.Dog"></bean>
16 
17     <!--Byname时:需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致-->
18     <!--Bytype时:需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致-->
19     <!--<bean id="people" class="com.ma.pojo.People" autowire="byType">
20         <property name="name" value="马爹爹呀"></property>
21        &lt;!&ndash; <property name="dog" ref="dog"></property>
22         <property name="cat" ref="cat"></property>&ndash;&gt;
23     </bean>-->
24 
25     <bean id="people" class="com.ma.pojo.People"></bean>
26 </beans>
View Code

关于注解配置,除了配置完上半部分之后,还有一部分即为重要,这些都是固定的

<context:annotation-config/>

操作完毕之后,便可以在对应的bean类进行操作,如下

 

 

 只要在对应的参数上增加上(@Autowired),便可以寻找到对应的类去执行方法;

@Autowired   a.是先通过名字(属性值相同,即id为类的名字,如id="cat")去寻找对应的类,其次是通过类型去寻找

       b.如果找不到对应的属性值相同的类(即没有id="cat"的类,但是可能有其他的,如:id="cat1"),就会通过类型去寻找

       c.通过类型去找有一个缺点:就是相对应的类型只能有一个对象,如果有多个的话,就会报错

       d.因此,我们需要去指定执行哪一个,才能继续运行。

posted @ 2021-04-13 16:29  古比  阅读(180)  评论(0编辑  收藏  举报