初学,如果有错误,欢迎大家指正。
IOC :控制反转,spring框架的核心之一
即,将对象的创建权交给spring来管理。
1.导入spring的核心包
|___Beans
|___Core
|___Context
|___Expression
2.配置applicationContext.xml
配置好beans标签
<bean id="" class=""></bean>
id属性为bean的名称信息
class属性为实体类的路径。
获取bean:
方法一(手动获取):
ApplicationContext ac = new ClassPathXmlApplicationContext(application.xml);
Object object = ac.getBean("配置文件中bean的id");
object.function();
方式二(自动扫描+注解)
applicationContext.xml中只需要配置自动扫描
<context:component-scan base-package="要扫描的路径"></context:component-scan>
在bean的类名上方添加注解@Component(value="该bean的id") 此处的value属性代表bean的id。
首先在需要使用该bean的类的类名上方添加注解@ContentConfiguration("applicationContext.xml")
将配置文件引入。然后在类的声明上添加注解@AutoWired(默认按类型装配) 或者@AutoWired @Qualifier(value="")(强制使用名称)与Resource(name="bean的ID")相同。
eg:
bean
@Component(value="Person")
class Person{
private String name;
private int age;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
service 实现类
@Component(value="userServiceImpl")
public void UserServiceImpl implements UserService{
@AutoWired
@Qualifier(value="Person")
private Person person;
public void showName(){
person.setName("小王");
System.out.println(person.getName);
}
}
test 测试类
@ContentConfiguration("applicationContext.xml")
public class Test{
@Resource(name="userServiceImpl")
private UserServiceImpl userImpl;
public static void main(String args[]){
userImpl.showName();
}
}