spring使用
来源:互联网 发布:dat打开软件 编辑:程序博客网 时间:2024/06/05 21:51
使用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");
- spring使用
- Spring使用
- Spring使用
- spring使用
- spring使用
- 使用Spring
- Spring-----4、使用Spring容器
- Spring (一) :简单使用Spring
- Spring--使用 Spring 进行单元测试
- Spring--Spring容器的使用
- Spring 读书笔记-----使用Spring容器
- 【Spring】使用Spring发送邮件
- 【Spring】使用Spring发送邮件
- 【Spring】使用Spring发送邮件
- 【Spring】使用Spring发送邮件
- 【Spring】使用Spring发送邮件
- [spring-boot] 使用spring session
- Spring-------使用Spring创建对象
- Python——【USACO 3.3.4】——Home on the Range
- 编译原理(十) SLR文法分析法-算法原理
- PHP程序员的技术成长规划
- 文件与数据接口基础
- cordova混合应用开发--安全控制--白名单
- spring使用
- CHROME插件
- c++ 静态变量 静态成员变量 静态成员函数
- 币值转换
- Python 静态方法 @staticmethod
- CocosCreator js 全局变量声明 require方式
- 微信公众号分享php代码(tp5)
- QNX驱动开发—进程调度和进程通信
- Https原理及实践