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 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd 9 "> 10 <!--注意配置xsd,要麼報錯:通配符的匹配很全面, 但沒法找到元素 'context:component-scan' 的聲明。--> 11 12 <context:component-scan base-package="com.ice.bean"/> 13 </beans>
base-package掃描的包,會包含子包.
寫法一: User類java
1 import org.springframework.stereotype.Component; 2 3 @Component(value = "user") //等同於在xml裏定義了 <bean id="user" class="" /> 4 public class User { 5 private String name; 6 private Integer age; 7 8 public String getName() { 9 return name; 10 } 11 12 public void setName(String name) { 13 this.name = name; 14 } 15 16 public Integer getAge() { 17 return age; 18 } 19 20 public void setAge(Integer age) { 21 this.age = age; 22 } 23 }
main方法:spring
ApplicationContext context = new ClassPathXmlApplicationContext("setting/applicationContext.xml"); User user = (User) context.getBean("user");
寫法二: User類app
1 import org.springframework.stereotype.Component; 2 3 @Component 4 public class User { 5 private String name; 6 private Integer age; 7 8 public String getName() { 9 return name; 10 } 11 12 public void setName(String name) { 13 this.name = name; 14 } 15 16 public Integer getAge() { 17 return age; 18 } 19 20 public void setAge(Integer age) { 21 this.age = age; 22 } 23 }
main方法:this
ApplicationContext context = new ClassPathXmlApplicationContext("setting/applicationContext.xml"); User user = context.getBean(User.class);
@Repository
@Service
@Controller 這三個註解跟Component一個效果
@Scope(scopeName = "prototype")//singleton prototype
@Value 放在字段上,是反射實現賦值;放在set方法上,是經過調用方法賦值.spa
@Autowired 按照類型 //import org.springframework.beans.factory.annotation.Autowired;
@Qualifier 按照名稱 //@Autowired @Qualifier 能夠一塊兒用
@Resource //import javax.annotation.Resource;prototype
...code