spring之通过注解方式配置Bean(二)

spring之通过注解方式配置Bean(二),第1张

概述上一节讲到了基本的基于注解配置Bean,但是每个Bean之间是没有关联的,现在我们想实现下面的功能。 基本目录: UserController.java 在这里调用UserService中的add方

上一节讲到了基本的基于注解的配置Bean,但是每个Bean之间是没有关联的,现在我们想实现下面的功能。

基本目录:

@H_404_6@

UserController.java

在这里调用UserService中的add方法。

@H_404_17@
package com.gong.spring.beans.annotation.controller;import org.springframework.stereotype.Controller; com.gong.spring.beans.annotation.service.UserService;@Controllerpublic class UserController {    private UserService userService;    voID execute() {        System.out.println("UserController的execute方法");        userService.add();    }}

UserService.java

在这里调用UserRepository中的save方法。

@H_404_17@
 com.gong.spring.beans.annotation.service; org.springframework.stereotype.Service; com.gong.spring.beans.annotation.repository.UserRepository;@Service UserService {     UserRepository userRepository;     add() {        System.out.println("UserService中的add方法");        userRepository.save();    }}

UserRepository.java

@H_404_17@
 com.gong.spring.beans.annotation.repository;interface UserRepository {     save();}

UserRepositoryImpl.java

@H_404_17@
 org.springframework.stereotype.Repository;@Repository(value="userRepository")class UserRepositoryImpl implements UserRepository{    @OverrIDe     save() {        // Todo auto-generated method stub        System.out.println("UserReposityImpl的save方法");    }}

Main.java

@H_404_17@
 com.gong.spring.beans.annotation; org.springframework.context.ApplicationContext; org.springframework.context.support.ClasspathXmlApplicationContext; com.gong.spring.beans.annotation.controller.UserController; Main {    static  main(String[] args) {        1.创建spring的IOC容器对象        ApplicationContext ctx = new ClasspathXmlApplicationContext("beans-annotation.xml");        2.从容器中获取Bean实例        UserController userController = (UserController) ctx.getBean("userController");        System.out.println(userController);     userController.execute();    }    }

beans-annotation.xml

@H_404_17@
<?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">            <!-- 配置springIOC容器扫描的包 -->        context:component-scan base-package="com.gong.spring.beans.annotation">    </context:component-scan>beans>

按照上节正常的配置,打印下输出结果:

会报空指针异常,是因为我们还没有在UserController中装配userService属性。

组件装配:<context:component-scan> 还会自动注册autowiredAnnotationBeanPostProcessor实例,该实例可以自动装配具有@autowired、@Resource和@INject注解的属性。

使用@autowired注解自动装配具有类型兼容的单个Bean属性:

构造器:普通字段,即使是非public,一切具有参数的方法都可使用@autowired注解。默认情况下,所有使用@autowired注解的属性都需要被设置。当spring找不到匹配的bean来装配属性时,会抛出异常。若某一属性不允许被设置,可以设置@autowired注解的required属性为false。默认情况下,当springIOC容器存在多个类型兼容的Bean时,通过类型的自动装配将无法工作。此时可在@QualifIEr注解里提供Bean的名称。spring允许对方法的入参标注@QualifIEr以指定注入bean的名称。@autowired注解也可以应用到数据类型的属性上,此时spring将会把所有匹配的bean进行自动装配。@autowired注解也可以应用在集合属性上,此时spring会读取集合的类型信息,然后自动装配给所有与之兼容的bean。@autowired用在jav.util.Map上时,若该Map的键值为string,那么spring将自动装配与Map值类型兼容的bean,此时bean的名称为键值。

讲了这么多,就是在要用@autowired让属性自动装配到相应的bean上,即变成:

@H_404_17@
@autowired UserService userService;@autowiredprivate UserRepository userRepository;

那么,就可以正常运行了,输出:

当然,还有另一种方式就是将@autowired对setter方法进行注解,而不是属性,即:

@H_404_17@
     UserRepository userRepository;    @autowired     setUserRepository(UserRepository userRepository) {        this.userRepository = userRepository;    }

这样也是可以的。

TestObject.java

@H_404_17@
 org.springframework.stereotype.Component;@Component TestObject {}

接下来我们在userRepositoryImpl中加入:

@H_404_17@
 org.springframework.beans.factory.annotation.autowired; org.springframework.stereotype.Repository; com.gong.spring.beans.annotation.TestObject;@Repository(value="userRepository" UserRepository{        @autowired    private TestObject testObject;    @OverrIDe    );        System.out.println(testObject);    }}

程序是可以运行的:

我们将TestObjec.java中的@Component注解去掉:

@H_404_17@
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfIEdDependencyException: Error creating bean with name 'userController': UnsatisfIEd dependency expressed through fIEld 'userService'; nested exception is org.springframework.beans.factory.UnsatisfIEdDependencyException: Error creating bean with name 'userService': UnsatisfIEd dependency expressed through method 'setUserRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfIEdDependencyException: Error creating bean with name 'userRepository': UnsatisfIEd dependency expressed through fIEld 'testObject'; nested exception is org.springframework.beans.factory.NoSuchBeanDeFinitionException: No qualifying bean of type 'com.gong.spring.beans.annotation.TestObject' available: expected at least 1 bean which qualifIEs as autowire candIDate. Dependency annotations: {@org.springframework.beans.factory.annotation.autowired(required=true)}

因为我们设置了:

@H_404_17@
private TestObject testObject;

没有找到该Bean,就会抛出异常。

我们再加上:说明不必要装配该属性

@H_404_17@
@autowired(required=false此时即使没有装配上TestObject也不会抛出异常了,即

(我们删除掉了@autowired(required=false)private TestObject testObject;System.out.println(testObject);)我们再新建一个UserJdbcRepository.java

@H_404_17@
 org.springframework.stereotype.Repository;@Repositoryclass UserJdbcRepository  UserRepository {    @OverrIDe     Todo auto-generated method stub        System.out.println("UserJdbcRepository的save方法");    }}

同时删除掉@Repository(value="userRepository")中的value属性,运行会抛出异常:没有一个唯一的bean

因此存在多个bean的实现类时,我们需要指定bean的名字,在调用时调用该名字,即:

@H_404_17@
     userRepository;    }

或者,我们这么指定要装配的bean的名字:

@H_404_17@
     UserRepository userRepository;    @autowired    @QualifIEr("userJdbcRepository")     userRepository;    }

输出:

也可以将该注解放入的setter方法中:

@H_404_17@
    voID setUserRepository(@QualifIEr("userJdbcRepository") UserRepository userRepository) {         userRepository;    }

@Resource和@Inject和@autowired类似,一般使用@autowired就足够了。

总结

以上是内存溢出为你收集整理的spring之通过注解方式配置Bean(二) 全部内容,希望文章能够帮你解决spring之通过注解方式配置Bean(二) 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1226948.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存