Spring完整版(二)

it2025-07-31  11

Spring完整版(二)

四、IOC创建对象的方式4.1、通过无参构造方法来创建(默认)4.2、通过有参构造方法来创建 五、Spring配置5.1、alias别名5.2、Bean的配置5.3、import 六、依赖注入(DI)6.1、构造器注入6.2、Set 注入 【重点】6.3、拓展方式注入6.3、Bean的作用域

四、IOC创建对象的方式

4.1、通过无参构造方法来创建(默认)

User.java public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void show(){ System.out.println("name="+name); } public User(){ System.out.println("User的无参构造!"); } } beans.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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.roc.pojo.User"> <property name="name" value="张万鹏"/> </bean> </beans> 测试类 public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //在执行getBean的时候, user已经创建好了 , 通过无参构造 User user = (User) context.getBean("user"); //调用对象的方法 user.show(); } }

结果可以发现,在调用show方法之前,User对象已经通过无参构造初始化了!

4.2、通过有参构造方法来创建

UserT.java public class UserT { private String name; public UserT(String name) { this.name = name; } public void setName(String name) { this.name = name; } public void show(){ System.out.println("name="+ name ); } } beans.xml 有三种方式编写 <!-- 第一种根据index参数下标设置 --> <bean id="usert" class="com.roc.pojo.UserT"> <!-- index指构造方法,下标从0开始 --> <constructor-arg index="0" value="张万鹏"/> </bean> <!-- 第二种根据参数类型设置 (不建议使用)--> <bean id="usert" class="com.roc.pojo.UserT"> <constructor-arg type="java.lang.String" value="zwp"/> </bean> <!-- 第三种根据参数名字设置 --> <bean id="usert" class="com.roc.pojo.UserT"> <!-- name指参数名 --> <constructor-arg name="name" value="张万鹏"/> </bean> 测试 public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserT usert = (UserT) context.getBean("usert"); usert.show(); } }

结论:在配置文件加载的时候。其中管理的对象都已经初始化了!

五、Spring配置

5.1、alias别名

alias 设置别名 , 为bean设置别名 , 可以设置多个别名

<!--设置别名:在获取Bean的时候可以使用别名获取--> <alias name="usert" alias="userNew"/> <alias name="usert" alias="userNew2"/>

5.2、Bean的配置

<!--bean就是java对象,由Spring创建和管理--> <!-- id:是bean的唯一标识符,如果没有配置id,name就是默认标识符 如果配置id,又配置了name,那么name是别名 name:别名,name可以设置多个别名,可以用逗号,分号,空格隔开 如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象; class:是bean的全限定名=包名+类名 --> <bean id="hello" name="hello2 h2,h3;h4" class="com.roc.pojo.User"> <property name="name" value="Spring"/> </bean>

5.3、import

团队的合作通过import来实现(将多个文件导入,合并为一个文件)

在总的配置文件(applicationContext.xml)中导入;

<import resource="{path}/beans.xml"/>

六、依赖注入(DI)

依赖注入(Dependency Injection,DI)。

依赖 : 指Bean对象的创建依赖于容器。Bean对象的依赖资源。

注入 : 指Bean对象所依赖的资源,由容器来设置和装配。

6.1、构造器注入

之前已经用过了!!!

6.2、Set 注入 【重点】

复杂类型 public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } 真实测试对象 public class Student { private String name; private Address address; private String[] books; private List<String> hobbys; private Map<String,String> card; private Set<String> games; private String wife; private Properties info; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String[] getBooks() { return books; } public void setBooks(String[] books) { this.books = books; } public List<String> getHobbys() { return hobbys; } public void setHobbys(List<String> hobbys) { this.hobbys = hobbys; } public Map<String, String> getCard() { return card; } public void setCard(Map<String, String> card) { this.card = card; } public Set<String> getGames() { return games; } public void setGames(Set<String> games) { this.games = games; } public String getWife() { return wife; } public void setWife(String wife) { this.wife = wife; } public Properties getInfo() { return info; } public void setInfo(Properties info) { this.info = info; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", address=" + address + ", books=" + Arrays.toString(books) + ", hobbys=" + hobbys + ", card=" + card + ", games=" + games + ", wife='" + wife + '\'' + ", info=" + info + '}'; } public void show(){ System.out.println("name="+ name + ",address="+ address.getAddress() + ",books=" ); for (String book:books){ System.out.print("<<"+book+">>\t"); } System.out.println("\n爱好:"+hobbys); System.out.println("card:"+card); System.out.println("games:"+games); System.out.println("wife:"+wife); System.out.println("info:"+info); } } 八种注入方式 <?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.roc.pojo.Address"> <property name="address" value="北京"/> </bean> <bean id="student" class="com.roc.pojo.Student"> <!--第一种:普通注入,value--> <property name="name" value="张万鹏"/> <!--第二种:Bean注入,ref--> <property name="address" ref="address"/> <!--第三种:数组注入--> <property name="books"> <array> <value>西游记</value> <value>红楼梦</value> <value>水浒传</value> </array> </property> <!--第四种:List注入,--> <property name="hobbys"> <list> <value>听歌</value> <value>看电影</value> <value>爬山</value> </list> </property> <!--第五种:Map注入--> <property name="card"> <map> <entry key="中国邮政" value="456456456465456"/> <entry key="建设" value="1456682255511"/> </map> </property> <!--第六种:Set注入--> <property name="games"> <set> <value>LOL</value> <value>BOB</value> <value>COC</value> </set> </property> <!--第七种:Null注入--> <property name="wife"> <null/> </property> <!--第八种:Properties注入--> <property name="info"> <props> <prop key="学号">20201022</prop> <prop key="性别"></prop> <prop key="姓名">小明</prop> </props> </property> </bean> </beans> 测试

6.3、拓展方式注入

p命名和c命名注入

User.java :【注意:这里没有有参构造器!】

public class User { 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; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } p命名空间注入 : 需要在头文件中加入约束文件 导入约束:xmlns:p="http://www.springframework.org/schema/p" <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--P(属性: properties)命名空间 , 属性依然要设置set方法--> <bean id="user" class="com.roc.pojo.User" p:name="张万鹏" p:age="21"></bean> </beans> c 命名空间注入 : 需要在头文件中加入约束文件 导入约束:xmlns:c="http://www.springframework.org/schema/c" <!--C(构造: Constructor)命名空间 , 属性依然要设置set方法--> <bean id="user2" class="com.roc.pojo.User" c:name="Roc" c:age="21"/>

发现问题:爆红了,刚才我们没有写有参构造!

解决:把有参构造器加上,这里也能知道,c 就是所谓的构造器注入!

测试代码:

@Test public void testUser(){ ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml"); User user = context.getBean("user2", User.class); System.out.println(user); }

6.3、Bean的作用域

在Spring中,那些组成应用程序的主体及由Spring IoC容器所管理的对象,被称之为bean。简单地讲,bean就是由IoC容器初始化、装配及管理的对象。

几种作用域中,request、session、application作用域仅在基于web的应用中使用(不必关心你所采用的是什么web应用框架),只能用在基于web的Spring ApplicationContext环境。

Singleton (Spring默认机制) 当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。要在XML中将bean定义成singleton,可以这样配置: <bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">

测试:

@Test public void testUser() { ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml"); User user = context.getBean("user2", User.class); User user2 = context.getBean("user2", User.class); System.out.println(user == user2); } Prototype 当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。在XML中将bean定义成prototype,可以这样配置: <bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/> Request

当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例;即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

<bean id="loginAction" class="com.something.LoginAction" scope="request"/>

针对每次HTTP请求,Spring容器会根据loginAction bean的定义创建一个全新的LoginAction bean实例,且该loginAction bean实例仅在当前HTTP request内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginAction bean定义创建的实例,将不会看到这些特定于某个请求的状态变化。当处理请求结束,request作用域的bean实例将被销毁。

Session

当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

<bean id="userPreferences" class="com.something.UserPreferences" scope="session"/>

针对某个HTTP Session,Spring容器会根据userPreferences bean定义创建一个全新的userPreferences bean实例,且该userPreferences bean仅在当前HTTP Session内有效。与request作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session中根据userPreferences创建的实例,将不会看到这些特定于某个HTTP Session的状态变化。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉。

最新回复(0)