使用bean.xml
ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
Person person = context.getBean("person",Person.class);person.info();
《Bean文件》
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="person" class="main.bean.Person">
<property name="name" value="yangyuqi"/>
<property name="age" value="111"/>
</bean>
</beans>
《Bean类》
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void info(){
System.out.println("一起来吃麻辣烫!");
System.out.println("name:"+getName()+" age:"+getAge());
}
}
- 首先会运行main()语句,Spring框架使用
ClassPathXmlApplicationContext()
首先创建一个容器。 - 这个容器从
Beans.xml
中读取配置信息,并根据配置信息来创建bean(也就是对象),每个bean有唯一的id。 - 然后通过
context.getBean()
找到这个id的bean,获取对象的引用。 - 通过对象的引用调用
printMessage()
方法来打印信息。
好了,这是你的第一个Spring应用。你已经学会用Eclipse新建Java项目,导入Spring和commons-logging库,编写Java源代码和XML配置文件,并且成功运行了。如果要更改输出,只需要修改XML文件中的value值,而不需要更改Java源文件。
下面的章节,我们将会在这个基础上体验Spring更多更强大的功能。
// ApplicationContext cApplicationContext = new AnnotationConfigApplicationContext("main.bean");
// CarService carService = cApplicationContext.getBean(CarService.class);
// carService.Addname("yangyuqi new Car");
@Repository
public class CarDao {
public void insertCar(String car) {
String insertMsg = String.format("insert into car %s", car);
System.out.println(insertMsg);
}
}
@Service
public class CarService {
@Autowired
CarDao carDao ;
public void Addname(String name) {
carDao.insertCar(name);
}
}
或者自动扫描
<!-- bean annotation driven -->
<context:annotation-config />
<context:component-scan base-package="main.bean" >
</context:component-scan>
ApplicationContext vContext = new ClassPathXmlApplicationContext("Bean.xml");
CarService carService = vContext.getBean(CarService.class);
carService.Addname("yangyuqi new Car");