老子有这样一个想法,我靠.xml里文件要写的太多了bean,我要用一个类,就要写一个bean,这不坑爹吗,
现在老子想要指定一个包,你丫自动把包内的所有类给我弄成bean,这个解决方法就是自动装配
applicationContext.xml
配置文件中需要加入<beans>标签的代码
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="...http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
,否则11行会报错 The prefix "context" for element "context:component-scan" is not bound.
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.pkg" />
//自动装配会扫描com.pkg这个包下的所有类,
//注入时,根据包中的类名注入,类名字符串首字母使用小写
//例如 Zoo zoo = (Zoo)context.getBean("zoo");
</beans>
Zoo.java
package com.pkg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
//import org.springframework.stereotype.Service;
@Component //这个注解表示,这是一个自动扫描的组件
//@Service("ZOO_SERVICE") 当这个注释取消时,注入时应该这样写 Zoo zoo = (Zoo)context.getBean("ZOO_SERVICE");并且这样会报错Zoo zoo = (Zoo)context.getBean("zoo");
public class Zoo {
@Autowired//自动装配animal,按类型,如果按名称装配,请使用@Resource
private Animal animal;
private String zooName;
public void setAnimal(Animal someAnimal) {
this.animal = someAnimal;
}
public void setZooName(String zooName) {
this.zooName = zooName;
}
public Animal getAnimal() {
return this.animal;
}
public String zooName() {
return this.zooName;
}
@Override
public String toString(){
return "Zoo [zooName=" + zooName + "][animal=(" + animal + ")]";
}
}
Animal.java
package com.pkg;
import org.springframework.stereotype.Component;
@Component
public class Animal {
private String species;
private int amount;
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
@Override
public String toString(){
return "Animal species=" + species + " amount=" + amount;
}
}
App.java
package com.pkg;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//Zoo zoo = (Zoo)context.getBean("ZOO_SERVICE");使用@Service时的注入用法
Zoo zoo = (Zoo)context.getBean("zoo");//类名首字母小写
System.out.println(zoo);
}
}
执行输出
Zoo [zooName=null][animal=(Animal species=null amount=0)]
追加
当某接口AInterface这样写时
@Autowired
AInterface aService;
框架就会去找
包含@Service("aService")这个注解的实现这个接口的类。