美文网首页Java
Spring中的Bean的配置形式

Spring中的Bean的配置形式

作者: 考拉考拉啊 | 来源:发表于2020-04-21 12:15 被阅读0次

Spring中Bean的配置形式有两种,基于XML文件的方式和基于注解的方式。

1.基于XML文件的方式配置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"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

<bean id="address" class="com.java.spring.autowire.Address" p:city="上海" p:street="南京路"></bean>

<bean id="car" class="com.java.spring.autowire.Car" p:brand="Audi" p:price="500000.0000"></bean>

<bean id="person" class="com.java.spring.autowire.Person" p:name="Tom" autowire="byType"></bean>

</beans>

像上面这样,在xml文件中使用<bean...></bean>标签设置Bean属性。

2.基于注解的方式配置Bean

把一个Bean加上注解放到IOC容器中,首先需要了解组件扫描。组件扫描(component scanning)是指Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件。特定组件包括:

@Component: 基本注解, 标识了一个受 Spring 管理的组件

@Respository: 标识持久层组件

@Service: 标识服务层(业务层)组件

@Controller: 标识表现层组件

对于扫描到的组件,

Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value

属性值标识组件的名称。当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明

<context:component-scan> :

base-package 属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类.当需要扫描多个包时, 可以使用逗号分隔;

如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern 属性过滤特定的类;

<context:include-filter> 子节点表示要包含的目标类;

<context:exclude-filter> 子节点表示要排除在外的目标类;

<context:component-scan> 下可以拥有若干个 <context:include-filter> 和 <context:exclude-filter> 子节点。

2.1 base-package属性

如图,创建如下的项目目录:

分别用TestObject,UserController,UserRepositoryImpl,UserService模拟基本注解,表现层,持久层和业务层。

TestObject.java

package com.java.spring.annotation;

import org.springframework.stereotype.Component;

@Component

public class TestObject {

}

UserController.java

package com.java.spring.annotation.controller;

import org.springframework.stereotype.Controller;

@Controller

public class UserController {

public void excute(){

System.out.println("UserController's excute...");

}

}

UserService.java

package com.java.spring.annotation.service;

import org.springframework.stereotype.Service;

@Service

public class UserService {

public void add(){

System.out.println("UserService's add...");

}

}

UserRepository.java

package com.java.spring.annotation.repository;

public interface UserRepository {

void save();

}

UserRepositoryImpl.java

package com.java.spring.annotation.repository;

import org.springframework.stereotype.Repository;

@Repository("userRepositoryImpl")

public class UserRepositoryImpl implements UserRepository {

@Override

public void save() {

    System.out.println("UserRepositoryImpl's save...");

}

}

为Bean添加注解之后还需要在 Spring 的配置文件中声明:

<context:component-scan base-package="com.java.spring.annotation"></context:component-scan>

 base-package="com.java.spring.annotation"意思是要扫描annotation包下的所有类。

写一个测试类Main.java:

package com.java.spring.annotation;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.java.spring.annotation.controller.UserController;

import com.java.spring.annotation.repository.UserRepositoryImpl;

import com.java.spring.annotation.service.UserService;

public class Main {

public static void main(String[] args){

ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");

UserRepositoryImpl uri=(UserRepositoryImpl) ctx.getBean("userRepositoryImpl");

System.out.println(uri);

TestObject to=(TestObject) ctx.getBean("testObject");

System.out.println(to);

        UserService us=(UserService) ctx.getBean("userService");

        System.out.println(us);

        UserController uc=(UserController) ctx.getBean("userController");

        System.out.println(uc);

}

}

运行后输出:

com.java.spring.annotation.repository.UserRepositoryImpl@4671e53b

com.java.spring.annotation.TestObject@2db7a79b

com.java.spring.annotation.service.UserService@6950e31

com.java.spring.annotation.controller.UserController@b7dd107

2.2 <context:include-filter>子节点

子节点表示要包含的目标类。使用<context:include-filter>时要将use-default-filters的值设置为false,默认为true。

比如在beans-annotation.xml中进行配置:

<context:component-scan base-package="com.java.spring.annotation" use-default-filters="false">

    <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>

</context:component-scan>

 则扫描到的组件只有@Repository("userRepositoryImpl")注解的持久层。

运行后输出:

com.java.spring.annotation.repository.UserRepositoryImpl@e720b71

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'testObject' is defined

at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)

at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)

at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)

at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)

at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)

at com.java.spring.annotation.Main.main(Main.java:12)

其他Bean显示未被定义。

2.3 <context:exclude-filter>子节点

子节点表示要排除在外的目标类,如下排除Repository类。

在beans-annotation.xml中进行配置:

<context:component-scan base-package="com.java.spring.annotation">

<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>

</context:component-scan>

Main.java中修改为:

public class Main {

public static void main(String[] args){

ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");

TestObject to=(TestObject) ctx.getBean("testObject");

System.out.println(to);

        UserService us=(UserService) ctx.getBean("userService");

        System.out.println(us);

        UserController uc=(UserController) ctx.getBean("userController");

        System.out.println(uc);

        UserRepositoryImpl uri=(UserRepositoryImpl) ctx.getBean("userRepositoryImpl");

        System.out.println(uri);

}

}

运行后输出:

com.java.spring.annotation.TestObject@757942a1

com.java.spring.annotation.service.UserService@4a87761d

com.java.spring.annotation.controller.UserController@66d1af89

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userRepositoryImpl' is defined

at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)

at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)

at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)

at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)

at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)

at com.java.spring.annotation.Main.main(Main.java:16)

将Repository排除,则扫描不到被@Repository("userRepositoryImpl")注解的Bean userRepositoryImpl,显示该Bean未被定义。

3.组件装配

<context:component-scan>

元素还会自动注册 AutowiredAnnotationBeanPostProcessor 实例, 该实例可以自动装配具有

@Autowired 和 @Resource 、@Inject注解的属性.

3.1 使用@Autowired自动装配所有Bean

@Autowired 注解自动装配具有兼容类型的单个 Bean属性。

构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解

默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false

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

@Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配.

@Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean.

@Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bean, 此时 Bean 的名称作为键值.

示例代码:使用Autowired注解

UserController.java

package com.java.spring.annotation.controller;

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

import org.springframework.stereotype.Controller;

import com.java.spring.annotation.service.UserService;

@Controller

public class UserController {

@Autowired

private UserService userservice;

public void excute(){

System.out.println("UserController's excute...");

userservice.add();

}

}

 UserService.java

package com.java.spring.annotation.service;

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

import org.springframework.stereotype.Service;

import com.java.spring.annotation.repository.UserRepository;

@Service

public class UserService {

@Autowired

private UserRepository userrepository;

public void add(){

System.out.println("UserService's add...");

userrepository.save();

}

}

UserRepositoryImpl.java

package com.java.spring.annotation.repository;

import org.springframework.stereotype.Repository;

@Repository("userRepository")

public class UserRepositoryImpl implements UserRepository {

@Override

public void save() {

    System.out.println("UserRepository's save...");

}

}

在主方法中测试:

public class Main {

public static void main(String[] args){

ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");

        UserController uc=(UserController) ctx.getBean("userController");

        System.out.println(uc);

        uc.excute();

}

主方法中调用uc.excute();指向 UserController.java

中的excute()方法,先执行System.out.println("UserController's

excute...");,再调用userservice.add();方法,此时需要使用Autowired注解UserService这个Bean,否则相当于UserService这个Bean未配置到IOC容器中去,出错;userservice.add();方法指向 UserService.java中的add()方法,先执行System.out.println("UserService's

add...");,再调用userrepository.save();方法,同理需要注解Bean,可以看到在UserRepositoryImpl.java中使用注解@Repository("userRepository")。

3.2 @Resource 和 @Inject

Spring

还支持 @Resource 和 @Inject 注解,这两个注解和 @Autowired 注解的功用类似。@Resource 注解要求提供一个

Bean 名称的属性,若该属性为空,则自动采用标注处的变量或方法名作为 Bean 的名称。@Inject 和 @Autowired

注解一样也是按类型匹配注入的 Bean, 但没有 reqired 属性。建议使用 @Autowired 注解。

4.泛型依赖注入

Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用。

BaseService<T>中引用了BaseRepository<T>,UserService为BaseService<T>的实现类,UserRepository为BaseRepository<T>的实现类,那么UserService和BaseService之间会自动地建立引用关系。

示例代码:

BaseService.java

package com.java.spring.generic.di;

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

public class BaseService<T>{

@Autowired

    private BaseRepository<T> repository;

    public void add(){

    System.out.println("add...");

    System.out.println(repository);

    }

}

BaseRepository.java

package com.java.spring.generic.di;

public class BaseRepository<T> {

}

User.java

package com.java.spring.generic.di;

public class User {

public User() {

}

}

UserService.java

package com.java.spring.generic.di;

import org.springframework.stereotype.Service;

@Service

public class UserService extends BaseService<User> {

}

UserRepository.java

package com.java.spring.generic.di;

import org.springframework.stereotype.Repository;

@Repository

public class UserRepository extends BaseRepository{

public UserRepository() {

}

}

在beans-generic-di.xml中进行配置:

<context:component-scan base-package="com.java.spring.generic.di"></context:component-scan>

在主方法中进行测试:

public static void main(String[] args){

ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-generic-di.xml");

UserService userService=(UserService) ctx.getBean("userService");

System.out.println(userService);

userService.add();

}

运行输出:

com.java.spring.generic.di.UserService@8e24743

add...

com.java.spring.generic.di.UserRepository@74a10858

在以上的代码中,BaseService中引用了BaseReponsitory,并且在BaseService的add方法中调用了BaseReponsitory的add方法。在他们的子类中,继承了这种关系。因此我们在测试方法中调用userService.add(); 也是可以成功地调用UserReponsitory中的add方法。

 wx搜索“程序员考拉”,专注java领域,一个伴你成长的公众号!

相关文章

网友评论

    本文标题:Spring中的Bean的配置形式

    本文链接:https://www.haomeiwen.com/subject/fckuihtx.html