2------一个简单的Spring项目
导入依赖
至于要弄清楚,每次需要导入哪些包,可以查看如下网站
https://juejin.im/entry/58ae5f5f2f301e0068ee6f9a
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.1.RELEASE</version> </dependency> </dependencies>
编写实体类
package demo1.com.sicheng.entity; public class Hello { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Hello(String name) { this.name = name; } public Hello() { } @Override public String toString() { return "Hello{" + "name='" + name + '\'' + '}'; } }
配置xml文件
<?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.xsd"> <bean id="hello" class="demo1.com.sicheng.entity.Hello"> <property name="name" value="hello"/> </bean> </beans>
编写测试类
import demo1.com.sicheng.entity.Hello; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { @Testo public void HelloTest(){ ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); Hello hello = (Hello)context.getBean("hello"); System.out.println(hello.toString()); } }
需要注意的
输出hello啦!!!
想不到吧,就是这么简单!!!
- 每一个实体类都可以去xml文件中,注册一下。
上述可以看出:
- name,通过set方法注入了,D:dependency,依赖
- 是通过无参构造方法构造的hello实体类
- Hello类被注入到了spring
修改一下xml文件
<?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.xsd"> <bean id="hello" class="demo1.com.sicheng.entity.Hello"> <constructor-arg name="name" value="1"/> </bean> </beans>
可以看出上述,hello实体类是通过有参构造方法构造的。
spring创建实体类的几种方法
类Hello
package demo1.com.sicheng.entity; public class Hello { private String name; private Person person; public String getName() { return name; } public void setName(String name) { this.name = name; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Hello() { } public Hello(String name, Person person) { this.name = name; this.person = person; } @Override public String toString() { return "Hello{" + "name='" + name + '\'' + ", person=" + person + '}'; } }
类Person
package demo1.com.sicheng.entity; public class Person { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(int age) { this.age = age; } public Person() { } @Override public String toString() { return "Person{" + "age=" + age + '}'; } }
第一种方式:通过无参构造方法!!
第二种方法:通过有参构造函数
由此可见,用constructor-arg就是调用有参函数成功的。
再来一个知识点---取别名,其实并没有什么用!