Spring_入门程序
程序员文章站
2024-02-26 18:53:04
...
1.新建web项目(结构如下)
2.导入jar包
3.导入日志配置
# Global logging configuration
log4j.rootLogger=info, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3.新建spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!-- bean:使容器创建Person对象 -->
<!-- name:相当于 Person person=new Person(); -->
<!-- class:类的位置 -->
<bean name="person" class="com.linxin.spring.pojo.Person"></bean>
</beans>
4.新建Person类
package com.linxin.spring.pojo;
public class Person {
private String name;
private Integer age;
public Person() {
super();
System.out.println("构造器被调用");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
5.新建测试类
package com.linxin.spring.pojo;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class IOCTest {
@SuppressWarnings("resource") //注解主要用在取消一些编译器产生的警告
@Test //测试注解
public void testCreatePerson() {
//创建容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//查找对象
Person p= (Person) applicationContext.getBean("person");
System.out.println(p);
}
}
6.测试结果
上一篇: 1000的阶乘问题
下一篇: java swing中实现拖拽功能示例