参考:https://www.cnblogs.com/zhanyao/p/4409231.html
即 对于扫描到的类,Spring默认命名为首字母小写。
@Controller
public class LoginController{
}
等价于
<bean id="loginController" class="XXX.LoginController"/>
也可以自定义id的名字:
package com.test;
import org.springframework.stereotype.Component;
/**
* 相当于<bean id="test"></bean>
*
*/
@Component("test")
public class ExampleTest {
public void show() {
System.out.println("hello world");
}
}
spring中注入方式,有属性set注入和构造函数注入
package com.spring.api;
public class Chinese implements Person {
private Axe axe;
public void setAxe(Axe axe) {
this.axe = axe;
}
public void useAxe() {
System.out.println("我打算去砍点柴火");
System.out.println(axe.chop());
}
}
package com.spring.api;
public class StoneAxe implements Axe {
public String chop() {
return "石斧砍柴好慢";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="chinese" class="com.spring.api.Chinese">
<property name="axe" ref="stoneAxe" />
</bean>
<bean id="stoneAxe" class="com.spring.api.StoneAxe" />
<bean id="win" class="javax.swing.JFrame" />
<bean id="date" class="java.util.Date" />
</beans>
属性注入:
<bean id="English_level" class="com.myspring.second.EnglishLevel">
<!-- set方法注入 -->
<property name="course">
<value>4级</value>
</property>
</bean>
<bean id="Math_level" class="com.myspring.second.MathCourse">
<!-- 构造函数注入 -->
<constructor-arg><value>1001</value></constructor-arg>
<constructor-arg><value>离散数学</value></constructor-arg>
</bean>
bean id="student" class="com.myspring.second.Student">
<property name="eng">
<ref bean="English_level"/>
</property>
<property name="mat">
<ref bean="Math_level"/>
</property>
</bean>
-------------------------------------------------------------------------------------
property 的 name 属性值,在实体 bean 中必须有对应的 set 方法,否则会报错
<bean id="student" class="com.myspring.second.Student">
<property name="eng">
<ref bean="English_level"/>
</property>
<property name="mat">
<ref bean="Math_level"/>
</property>
</bean>