Spring学习总结一(续2)

16 通过静态工厂方法配置bean

    这里我们新建一个包com.alibaba.beans.factory,然后把前面总结一里面的Car类复制过来修改了一下(下面给出代码),然后新建一个staticfactory的类去构造静态工厂方法。总结将在代码后面给出,读者可以参考总结、代码以及代码上的注释去学习通过静态方法配置bean。

package com.alibaba.beans.factory;

public class Car
{
	private String brand;
	private double price;

	public String getBrand()
	{
		return brand;
	}

	public void setBrand(String brand)
	{
		this.brand = brand;
	}

	public double getPrice()
	{
		return price;
	}

	public void setPrice(double price)
	{
		this.price = price;
	}

	@Override
	public String toString()
	{
		return "Car [brand=" + brand + ", price=" + price + "]";
	}

	public Car()
	{
		System.out.println("Car's Constructor ...");
	}

	public Car(String brand, double price)
	{
		this.brand = brand;
		this.price = price;
	}
}
package com.alibaba.beans.factory;
import java.util.HashMap;
import java.util.Map;

public class StaticFactory
{
	/*
	 * 静态工厂方法:直接调用某一个类的静态方法就可可以返回bean的实例
	 */
	private static Map<String, Car> cars = new HashMap<>();

	static 
	{
		cars.put("audi", new Car("audi", 300000));
		cars.put("ford", new Car("ford", 200000));
	}
	
	//静态工厂方法
	public static Car getCar(String name)
	{
		return cars.get(name);
	}
	
}
<?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="car" class="com.alibaba.beans.factory.StaticFactory"
		factory-method="getCar">
		<constructor-arg value="audi"></constructor-arg>
	</bean>

</beans>
测试主类:

package com.alibaba.beans.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
		Car car = (Car) ctx.getBean("car");
		
		System.out.println(car);
	}
}
总结 :调用静态工厂方法创建 Bean是将对象创建的过程封装到静态方法中. 当客户端需要对象时, 只需要简单地调用静态方法, 而不需关心创建对象的细节.要声明通过静态方法创建的 Bean, 需要在 Bean 的 class 属性里指定拥有该工厂的方法的类, 同时在 factory-method 属性里指定工厂方法的名称. 最后, 使用 <constrctor-arg> 元素为该方法传递方法参数.

17 通过实例工厂方法配置bean

    实例工厂方法配置bean和静态工厂方法配置bean有点相似,只需要新建一个实例工厂类,然后在配置文件中做修改即可.同样先给出代码,代码下面做一个总结.(Car类和上面的一样,学习时请复制过来即可)

package com.alibaba.beans.factory;

import java.util.HashMap;
import java.util.Map;

public class InstanceFactory
{
	private Map<String, Car> cars = new HashMap<>();

	public InstanceFactory()
	{
		cars.put("audi", new Car("audi", 300000));
		cars.put("ford", new Car("ford", 200000));
	}

	public Car getCar(String brand)
	{
		return cars.get(brand);
	}
}
package com.alibaba.beans.factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
		Car car = (Car) ctx.getBean("car");

		System.out.println(car);

		System.out.println("----------------------我是测试分割线-----------------------------");
		Car car1 = (Car) ctx.getBean("car1");

		System.out.println(car1);
	}
}
<?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="car" class="com.alibaba.beans.factory.StaticFactory"
		factory-method="getCar">
		<constructor-arg value="audi"></constructor-arg>
	</bean>

	<span style="color:#FF0000;"><!-- 配置工厂的实例 --></span>
	<bean id="<span style="color:#33FF33;">carFactory</span>" class="com.alibaba.beans.factory.InstanceFactory"></bean>

	<!-- 通过实例工厂方法来配置bean -->

	<bean id="car1" factory-bean="<span style="color:#33FF33;">carFactory</span>" factory-method="getCar">
		<constructor-arg value="ford"></constructor-arg>
	</bean>
</beans>
总结:实例工厂方法: 将对象的创建过程封装到另外一个对象实例的方法里. 当客户端需要请求对象时, 只需要简单的调用该实例方法而不需要关心对象的创建细节.要声明通过实例工厂方法创建的 Bean:
  • 在 bean 的factory-bean属性里指定拥有该工厂方法的Bean
  • 在 factory-method 属性里指定该工厂方法的名称
  • 使用 construtor-arg 元素为工厂方法传递方法参数

18 通过注解配置bean

    组件扫描(component scanning):  Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件.特定组件包括:(1) @Component: 基本注解, 标识了一个受 Spring 管理的组件;(2) @Respository: 标识持久层组件;(3) @Service: 标识服务层(业务层)组件;(4) @Controller: 标识表现层组件。对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称。这里同样为了学习通过注解配置bean,我们新建一个com.alibaba.beans.annoation的包,然后在其下面分别建立上面4层的子包。这里我只是去用这个4个注解去模拟一下实际开发中的流程,便于我们了解和认识注解配置bean。下面给出各个类代码以及配置文件代码:

package com.alibaba.beans.annoation.controller;

import org.springframework.stereotype.Controller;

@Controller
public class UserController
{
	public void execute()
	{
		System.out.println("UserController...");
	}
}
package com.alibaba.beans.annoation.service;

import org.springframework.stereotype.Service;

@Service
public class UserService
{
	public void add()
	{
		System.out.println("User Service's add ....");
	}
}
package com.alibaba.beans.annoation.respository;

public interface UserRepository
{
	void save();
}
package com.alibaba.beans.annoation.respository;

import org.springframework.stereotype.Repository;

@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository
{

	@Override
	public void save()
	{
		System.out.println("UserRespositoryImpl's save...");
	}

}
package com.alibaba.beans.annoation;

import org.springframework.stereotype.Component;

@Component
public class TestObject
{

}
package com.alibaba.beans.annoation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.alibaba.beans.annoation.controller.UserController;
import com.alibaba.beans.annoation.respository.UserRepository;
import com.alibaba.beans.annoation.respository.UserRepositoryImpl;
import com.alibaba.beans.annoation.service.UserService;

public class Main
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annoation.xml");

		TestObject testObject = (TestObject) ctx.getBean("testObject");
		System.out.println("testObject: " + testObject);

		UserController uc = (UserController) ctx.getBean("userController");
		System.out.println("userController: " + uc);


		UserRepository ur = (UserRepository) ctx.getBean("userRepository");
		System.out.println("userRespository: " + ur);
		
		UserService us = (UserService) ctx.getBean("userService");
		System.out.println("userService: " + us);

	}
}
<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- 指定IOC容器中扫描的包 -->
	<context:component-scan base-package="com.alibaba.beans.annoation"></context:component-scan>

</beans>

总结:组件扫描(component scanning): Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件.特定组件包括:(1).@Component: 基本注解, 标识了一个受 Spring 管理的组件;(2).@Respository: 标识持久层组件;(3).@Service: 标识服务层(业务层)组件;(4).@Controller: 标识表现层组件。对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称。当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明 <context:component-scan> :base-package 属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类.当需要扫描多个包时, 可以使用逗号分隔.如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern属性过滤特定的类。同时还可以使用<context:include-filter>标签来表示要包含的目标类,使用<context:exclude-filter>标签表示排除目标类。给出利用resource-pattern属性的代码(修改了上面的代码,给出修改后的代码:)

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- 指定IOC容器中扫描的包 -->
	<!-- 可以通过resource-pattern属性扫描资源,此时需要把Main类中的被过滤掉的bean的代码注释掉 否则会抛出异常 因为你已经把那几个类给过滤掉了 
		你还要获取bean实例的话 肯定会找不到啊,所以就会抛出异常 -->
	<context:component-scan base-package="com.alibaba.beans.annoation"
		resource-pattern="respository/*.class">

	</context:component-scan>

</beans>
package com.alibaba.beans.annoation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.alibaba.beans.annoation.controller.UserController;
import com.alibaba.beans.annoation.respository.UserRepository;
import com.alibaba.beans.annoation.respository.UserRepositoryImpl;
import com.alibaba.beans.annoation.service.UserService;

public class Main
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annoation.xml");

		// TestObject testObject = (TestObject) ctx.getBean("testObject");
		// System.out.println("testObject: " + testObject);
		//
		// UserController uc = (UserController) ctx.getBean("userController");
		// System.out.println("userController: " + uc);
		//
		// UserService us = (UserService) ctx.getBean("userService");
		// System.out.println("userService: " + us);

		UserRepository ur = (UserRepository) ctx.getBean("userRepository");
		System.out.println("userRespository: " + ur);

	}
}

下面给出一个使用<context:exclude-filter>标签的例子的配置文件:

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- 指定IOC容器中扫描的包 -->
	<!-- 可以通过resource-pattern属性扫描资源,此时需要把Main类中的被过滤掉的bean的代码注释掉 否则会抛出异常 因为你已经把那几个类给过滤掉了 
		你还要获取bean实例的话 肯定会找不到啊,所以就会抛出异常 -->
	<!-- <context:component-scan base-package="com.alibaba.beans.annoation" -->
	<!-- resource-pattern="respository/*.class"> -->

	<!-- </context:component-scan> -->

	<context:component-scan base-package="com.alibaba.beans.annoation">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Repository" />
	</context:component-scan>

</beans>
下面给出使用<context:include-filter>标签的例子,记得看一下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" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- 指定IOC容器中扫描的包 -->
	<!-- 可以通过resource-pattern属性扫描资源,此时需要把Main类中的被过滤掉的bean的代码注释掉 否则会抛出异常 因为你已经把那几个类给过滤掉了 
		你还要获取bean实例的话 肯定会找不到啊,所以就会抛出异常 -->
	<!-- <context:component-scan base-package="com.alibaba.beans.annoation" -->
	<!-- resource-pattern="respository/*.class"> -->

	<!-- </context:component-scan> -->

	<!-- <context:component-scan base-package="com.alibaba.beans.annoation"> -->
	<!-- <context:exclude-filter type="annotation" -->
	<!-- expression="org.springframework.stereotype.Repository" /> -->
	<!-- </context:component-scan> -->

	<span style="color:#ff0000;"><!-- 如果想仅包含某一个目标类文件 需要与use-default-filter标签配合使用,否则在同一个子包下的其他类无法被排除 --></span>
	<context:component-scan base-package="com.alibaba.beans.annoation"
		use-default-filters="false">
		<context:include-filter <span style="color:#ff0000;">type="annotation</span>"
			expression="org.springframework.stereotype.Repository" />
	</context:component-scan>


</beans>
对于上面的<context:include-filter>标签和<context:exclude-filter>标签可以使用下面这么几种类型的过滤表达式,主要用到
的是前两种:


19 组件装配

    当bean之间有依赖关系时,我们同样可以通过注解去配置bean之间的依赖关系,接下来我们去配置上面Controller、Service、repository之间的依赖关系。在上面代码上做如下修改:

package com.alibaba.beans.annoation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.alibaba.beans.annoation.controller.UserController;
import com.alibaba.beans.annoation.respository.UserRepository;
import com.alibaba.beans.annoation.respository.UserRepositoryImpl;
import com.alibaba.beans.annoation.service.UserService;

public class Main
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annoation.xml");

		TestObject testObject = (TestObject) ctx.getBean("testObject");
		System.out.println("testObject: " + testObject);

		UserController uc = (UserController) ctx.getBean("userController");
		System.out.println("userController: " + uc);

		uc.execute();
		// UserService us = (UserService) ctx.getBean("userService");
		// System.out.println("userService: " + us);
		//
		// UserRepository ur = (UserRepository) ctx.getBean("userRepository");
		// System.out.println("userRespository: " + ur);

	}
}
package com.alibaba.beans.annoation.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.alibaba.beans.annoation.service.UserService;

@Controller
public class UserController
{
	@Autowired
	private UserService userService;
	public void execute()
	{
		System.out.println("UserController...");
		userService.add();
	}
}
package com.alibaba.beans.annoation.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.beans.annoation.respository.UserRepositoryImpl;

@Service
public class UserService
{
	@Autowired
	private UserRepositoryImpl userRespository;
	
	public void add()
	{
		System.out.println("User Service's add ....");
		userRespository.save();
	}
}
<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- 指定IOC容器中扫描的包 -->
	<!-- 可以通过resource-pattern属性扫描资源,此时需要把Main类中的被过滤掉的bean的代码注释掉 否则会抛出异常 因为你已经把那几个类给过滤掉了 
		你还要获取bean实例的话 肯定会找不到啊,所以就会抛出异常 -->
	<!-- <context:component-scan base-package="com.alibaba.beans.annoation" -->
	<!-- resource-pattern="respository/*.class"> -->

	<!-- </context:component-scan> -->

	<!-- <context:component-scan base-package="com.alibaba.beans.annoation"> -->
	<!-- <context:exclude-filter type="annotation" -->
	<!-- expression="org.springframework.stereotype.Repository" /> -->
	<!-- </context:component-scan> -->

	<!-- 如果想仅包含某一个目标类文件 需要与use-default-filter标签配合使用,否则在同一个子包下的其他类无法被排除 -->
	<!-- <context:component-scan base-package="com.alibaba.beans.annoation" -->
	<!-- use-default-filters="false"> -->
	<!-- <context:include-filter type="annotation" -->
	<!-- expression="org.springframework.stereotype.Repository" /> -->
	<!-- </context:component-scan> -->
	<context:component-scan base-package="com.alibaba.beans.annoation"></context:component-scan>

</beans>
总结:<context:component-scan> 元素还会自动注册 AutowiredAnnotationBeanPostProcessor实例, 该实例可以自动装配具有 @Autowired 和 @Resource 、@Inject注解的属性.Autowired 注解自动装配具有兼容类型的单个Bean属性、构造器、普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解。默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false。

    默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 @Qualifier 指定注入 Bean 的名称。

接下来我们为了学习上面通过@Qualifier指定具体bean的知识点,在com.alibaba.beans.annoation.repository下面新建一个UserJdbcRepository类实现了Repository的接口。这样如果我们不指定具体的接口,Repository的实例就有两个。所以当我们没有指定时,IOC容器就不知道加载哪个bean,就会抛出异常。下面给出类代码:

package com.alibaba.beans.annoation.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alibaba.beans.annoation.respository.UserRepository;

@Service
public class UserService
{
	<span style="color:#FF0000;">// 这里我们装配的是一个UserRespository类型的实例变量,而实现这个接口的类有两个,此时如果不指定Spirng
	// IOC不知道去装配哪个类的实例就会抛出异常,此时我们就需要指定;</span>
	@Autowired
	@Qualifier("userRepositoryImpl")
	private UserRepository userRespository;

	public void add()
	{
		System.out.println("User Service's add ....");
		userRespository.save();
	}
}
package com.alibaba.beans.annoation.respository;

import org.springframework.stereotype.Repository;

@Repository
public class UserJdbcRespository implements UserRepository
{

	@Override
	public void save()
	{
		System.out.println("UserJdbcRespository save...");
	}

}
    其他的类不变,直接把上面的其他类和配置文件复制过来就可以了。@Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配。@Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean。@Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bea n, 此时 Bean 的名称作为键值。

20 泛型依赖注入

    Spring4.x的新特性:泛型依赖注入。当我们在实际开发时,我们的Service和Repository里面就是creat、retrieve、update、delete的操作,所以当Spring提供了泛型依赖注入时,我们的实际开发就会轻松很多。下面我们给出一个UML类图供大家去理解我们接下来要说的类之间的关系。


可以看到我们提供了两个泛型类BaseService<T>和BaseRepository<T>,它们之间建立了关联关系,所以他们的子类之间也会自动建立了关联关系。接下来为了便于理解,我们建立一个com.alibaba.beans.generic.di的包,下面给出这个包下的类及其配置文件:
package com.alibaba.beans.generic.di;

public class BaseRepository<T>
{

}
package com.alibaba.beans.generic.di;

import org.springframework.beans.factory.annotation.Autowired;

public class BaseService<T>
{
	@Autowired
	protected BaseRepository<T> repository;
	
	public void add()
	{
		System.out.println("add...");
		System.out.println(repository);
	}
}
package com.alibaba.beans.generic.di;

public class User
{

}
package com.alibaba.beans.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>
{

}
package com.alibaba.beans.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>
{

}
package com.alibaba.beans.generic.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-generic-di.xml");

		UserService userService = (UserService) ctx.getBean("userService");
		userService.add();
	}
}
<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<context:component-scan base-package="com.alibaba.beans.generic.di"></context:component-scan>
<span style="font-family:SimSun;"></beans></span>

至此,Spring学习总结一结束,给出代码下载地址:spring学习总结一代码下载地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值