spring实操
程序员文章站
2024-03-22 10:59:04
...
1.首先创建一个maven工程(使用idea这里就不做演示了)
2. 创建Book类与Author类·
Book 类
public class Book {
private String bookName;
private String author;
public Book(){
System.out.println("This is Book constructor.");
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
System.out.println("This is Book setBookName().");
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
System.out.println("This is Book setAuthor().");
this.author = author;
}
public void printBookInfo() {
System.out.println("Book Name:" + this.bookName + ",Author:" + this.author);
}
}
Author类
public class Author {
private String name;
private int age;
public Author() {
System.out.println("This is Author constructor.");
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("This is Author setName().");
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
System.out.println("This is Author setAge().");
this.age = age;
}
public void printAuthorInfo() {
System.out.println("Name:" + this.name + ",Age:" + this.age);
}
}
3.按照传统方式创建对象:
public void test1() {
Book book = new Book();
book.setAuthor("李四");
book.setBookName("平凡的世界");
book.printBookInfo();
}
执行结果:
4.使用spring框架注入bean的形式调用:
<?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="bookId" class="com.lize.spring.model.Book">
<property name="author" value="李四"></property>
<property name="bookName" value="平凡的世界"></property>
</bean>
<bean id="authorId" class="com.lize.spring.model.Author">
<property name="age" value="26"></property>
<property name="name" value="李四"></property>
</bean>
</beans>
5.获取bean实例对象:
public void getSpring() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Book book = applicationContext.getBean("bookId", Book.class);
book.printBookInfo();
}
6.执行结果:
运行结果与传统定义方式一样,只是多了一些spring的日志。
在上面的代码中,我们并未使用new运算符来创建Book类的实例,但是却可以得到Book类的实例,这就是Spring的强大之处,所有类的实例的创建都不需要应用程序自己创建,而是交给Spring容器来创建及管理。
7.spring是在什么时候初始化的对象,我们可以打断点调试查看。
调试得知在初始化ApplicationContext对象的时候对注入bean的实例进行了初始化,之后在使用的时候直接get即可获取。
上一篇: 经典Java面试题收集(三)
下一篇: Leetcode 867 - 转置矩阵
推荐阅读
-
spring实操
-
实操strace
-
Spring指定Bean的初始化方法和销毁方法 博客分类: Spring
-
Spring与Hibernate的整合 博客分类: 整合 hibernatespring
-
Struts2+Spring2.5+Hibernate3.3整合开发 博客分类: 整合
-
Mybatis jar+mybatis-spring.jar官网下载地址 博客分类: springjavamybatis
-
Spring所使用的两种代理 博客分类: spring
-
SpringMVC中JSP取不到ModelAndView的数据的原因 博客分类: java Java spring springMVC
-
Spring3+Struts2+SpringJDBC注解实现 博客分类: spring spring
-
Spring 官网下载地址 博客分类: javaspring springjava