使用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");