标签:例子 text his string spring destory com context contex
上次写到spring是什么,说了很多的废话,那么从现在起 来看看spring如何使用 写几个例子
1 如何使用 spring
1.1导包
在导入四个包的基础上再导入日志包总共六个包 如下图
1.2 导完包后 创建User对象 代码如下
package com.lijun.bean;
public class User {
public User() {
}
private String name;
private int age;
private Car car;
public User(String name,Car car){
System.out.println("User(String name,Car car)!!!");
this.name = name;
this.car = car;
}
public User(Car car,String name){
System.out.println("User(Car car,String name)!!!");
this.name = name;
this.car = car;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public User(String name,int age){
this.age=age;
this.name=name;
}
public User(int age,String name){
this.age=age;
this.name=name;
}
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 init(){
System.out.println("我是初始化方法");
}
public void destory(){
System.out.println("我是销毁方法");
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
1.3 书写配置文件 注册对象到spring容器 文件格式为.xml
建议改配置文件名叫 applicationContext 文件位置任意 但是建议src下,另外需要引入约束 约束就不在叙述如下图
创建的xml文件 代码如下
<?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-4.2.xsd ">
<bean name="UserDao" class="xingdongpai.UserDaoImpl"></bean>
</beans>
1.4 代码测试如下
package xingdongpai;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void demo2(){
//创建工厂类
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext1.xml");
UserDao bean1 = (UserDao)ac.getBean("UserDao");
bean1.sayLijun();
System.out.println(bean1);
}
}
1.5测试结果下图
标签:例子 text his string spring destory com context contex
原文地址:https://www.cnblogs.com/lijun6/p/10339014.html