Spring Bean装载方式代码实例解析

这篇文章主要介绍了Spring Bean装载方式代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Bean的装配方式

Bean的装配可以理解为依赖关系注入

基于XML的装配

  a) 设值注入

i.要求:

  • Bean 类必须提供一个默认的无参构造方法。
  • Bean 类必须为需要注入的属性提供对应的setter方法。

  b) 构造注入

package com.itheima.assemble;

import java.util.List;

public class User {
  private String username;
  private Integer password;
  private List<String> List;
  /*
   * 1.使用构造注入
   * 1.1提供所有带参数的有参构造方法
   */
  public User(String username,Integer password,List<String> List){
    super();
    this.username = username;
    this.password = password;
    this.List = List;
  }
  /*
   * 2.使用设值注入
   * 2.1提供默认空构造方法
   * 2.2为所有属性提供setter方法
   */
  public User(){

  }
  public void setUsername(String username) {
    this.username = username;
  }
  public void setPassword(Integer password) {
    this.password = password;
  }
  public void setList(List<String> list) {
    List = list;
  }
  @Override
  /*
   * (non-Javadoc)
   * @see java.lang.Object#toString()
   * 为了输出是看到结果,重写toString()方法
   */
  public String toString() {
    return "User [username=" + username + ", password=" + password + ", List=" + List + "]";
  }
}
<?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">
<!-- 1.使用构造注入方式装配User实例 -->
<bean id="user1" class="com.itheima.assemble.User">
<constructor-arg index="0" value="tom"></constructor-arg>
<constructor-arg index="1" value="123456"></constructor-arg>
<constructor-arg index="2">
  <list>
  <value>"constructorvalue1"</value>
  <value>"constructorvalue2"</value>
  </list>
</constructor-arg>
</bean>
<!-- 2.使用设值注入装配User实例 -->
<bean id="user2" class="com.itheima.assemble.User">
  <property name="username" value="张三"></property>
  <property name="password" value="654321"></property>
  <!-- 注入list集合 -->
  <property name="list">
    <list>
      <value>"setlistvalue1"</value>
      <value>"setlistvalue2"</value>
    </list>
  </property>
</bean>
</beans>

<constructor -arg >元素用于定义构造方法的参数,子元素<Iist>来为Use r 类中对应的list集合属性注入值。

其中<property>元素用于调用Bean实例中的setter方法完成属性赋值,从而完成依赖注入。

package com.itheima.assemble;

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

public class XmlBeanAssembleTest {
  public static void main(String[] args) {
    //定义配置文件路径
    String xmlPath = "com/itheima/assemble/beans5.xml";
    //加载配置文件
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
    //构造方式输出结果
    System.out.println("构造方式:");
    System.out.println(applicationContext.getBean("user1"));
    //设值方式输出结果
    System.out.println("设值方式:");
    System.out.println(applicationContext.getBean("user2"));
  }
}

2.基于Annotation的装配

package com.itheima.annotation;

public interface UserDao {
  public void save();
}
package com.itheima.annotation;

import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDaoImpl implements UserDao{
  public void save(){
    System.out.println("userdao...save...");
  }
}

先使用@Repository 注解将UserDaolmpl 类标识为Spring 中的Bean,其写法相当于配置文件中<bean id="userDao" class="com.itheima.annotation.UserDaolmpl"/>

package com.itheima.annotation;

public interface UserService {
  public void save();
}
package com.itheima.annotation;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService{
  @Resource(name="userDao")
  private UserDao userDao;
  @Override
  public void save() {
    // TODO Auto-generated method stub
    //调用userDao中的save()方法
    this.userDao.save();
    System.out.println("userservice...save...");
  }
  public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
  }

}

@Service 注解将UserServicelmpl 类标识为Spring中的Bean,这相当于配置文件中<bean id="userService" class="com.itheima.annotation.UserServicelmpl”/> 的编写;然后使用@Resource 注解标注在属性userDao上,这相当于配置文件中<property name="userDao" ref="userDao“/>的写法。

package com.itheima.annotation;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

@Controller("userController")
public class UserController {
  @Resource(name="userService")
  private UserService userService;
  public void save(){
    this.userService.save();
    System.out.println("userControlle...save...");
  }
  public void setUserService(UserService userService) {
    this.userService = userService;
  }

}

Controller 注解标注了UserController 类,这相当于在配置文件中编写<bean id="userControll er" class="com .itheima.annotation.UserController"/>; 然后使用了@Resource 注解标注在userService 属性上,这相当于在配置文件中编写<propertyname="userService" ref="userService" />

<?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-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 使用context命名空间,在配置文件中开启相应的注释处理器 -->
<context:component-scan base-package="com.itheima.annotation"></context:component-scan>

</beans>
package com.itheima.annotation;

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

public class AnnotationAssembleTest {
  public static void main(String[] args) {
    String xmlPath = "com/itheima/annotation/beans6.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
    //获取UserController实例
    UserController userController = (UserController)applicationContext.getBean("userController");
    //调用UserController中的save()方法
    userController.save();
  }
}

3.自动装配

<?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-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 使用bean元素的autowire属性完成自动装配 -->
<bean id="userDao" class="com.itheima.annotation.UserDaoImpl"></bean>
<bean id="userService" class="com.itheima.annotation.UserServiceImpl" autowire="byName"></bean>
<bean id="userController" class="com.itheima.annotation.UserController" autowire="byName"></bean>
</beans>

增加了autowire 属性,并将其属性值设置为byName 。在默认情况下,配置文件中需要通过ref 来装配Bean ,但设置了autowire=" byName"后,Spring 会自动寻找userServiceBean 中的属性,并将其属性名称与配置文件中定义的Bean 做匹配。由于UserServicelmpl 中定义了userDao 属'性及其setter 方法,这与配置文件中id 为userDao 的Bean 相匹配,所以Spring会自动地将id 为userDao 的Bean 装配到id 为userService 的Bean 中。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Spring实战之使用静态工厂方法创建Bean操作示例

    本文实例讲述了Spring实战之使用静态工厂方法创建Bean操作.分享给大家供大家参考,具体如下: 一 配置 <?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" x

  • 详解Java的Spring框架下bean的自动装载方式

    Spring容器可以自动装配相互协作bean之间的关系,这有助于减少对XML配置,而无需编写一个大的基于Spring应用程序的较多的<constructor-arg>和<property>元素. 自动装配模式: 有下列自动装配模式,可用于指示Spring容器使用自动装配依赖注入.使用<bean/>元素的autowire属性为一个bean定义中指定自动装配模式. byName模式 这种模式规定由自动装配属性名称.Spring容器在外观上自动线属性设置为byName的XML

  • Spring实战之获取其他Bean的属性值操作示例

    本文实例讲述了Spring实战之获取其他Bean的属性值操作.分享给大家供大家参考,具体如下: 一 配置 <?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xml

  • Spring如何使用注解的方式创建bean

    这篇文章主要介绍了Spring如何使用注解的方式创建bean,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 第一种使用配置类的方式 1.创建一个bean package com.springbean; public class Person { private String name; private Integer age ; public Person(String name, Integer age) { this.name = name

  • Spring实战之注入嵌套Bean操作示例

    本文实例讲述了Spring实战之注入嵌套Bean操作.分享给大家供大家参考,具体如下: 一 配置 <?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:sch

  • spring boot装载自定义yml文件

    yml格式的配置文件感觉很人性化,所以想把项目中的.properties都替换成.yml文件,主要springboot自1.5以后就把@configurationProperties中的location参数去掉,各种查询之后发现可以用YamlPropertySourceLoader去装载yml文件,上代码 public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ResourceLoader loade

  • Spring实战之Bean定义中的SpEL表达式语言支持操作示例

    本文实例讲述了Spring实战之Bean定义中的SpEL表达式语言支持操作.分享给大家供大家参考,具体如下: 一 配置 <?xml version="1.0" encoding="GBK"?> <!-- 指定Spring配置文件的根元素和Schema 导入p:命名空间和util:命名空间的元素 --> <beans xmlns="http://www.springframework.org/schema/beans"

  • SpringBoot如何统一配置bean的别名

    这篇文章主要介绍了SpringBoot如何统一配置bean的别名,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 所谓别名, 就是在mappper.xml配置文件中像什么resultType="xxx" 不需要写全限定类名, 只需要写类名即可. 配置方式有两种: 1. 在 application.yml中 #mybatis相关配置 mybatis: type-aliases-package: com.zzuli.domain 2. 在a

  • Spring Bean实例化实现过程解析

    这篇文章主要介绍了Spring Bean实例化实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Bean的实例化 1.构造器实例化:Spring容器通过Bean对应类中默认的无参构造方法来实例化Bean package com.itheima.instance.constructor; public class Bean1 { } <?xml version="1.0" encoding="UTF-8&quo

  • Spring Bean装载方式代码实例解析

    这篇文章主要介绍了Spring Bean装载方式代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Bean的装配方式 Bean的装配可以理解为依赖关系注入 基于XML的装配 a) 设值注入 i.要求: Bean 类必须提供一个默认的无参构造方法. Bean 类必须为需要注入的属性提供对应的setter方法. b) 构造注入 package com.itheima.assemble; import java.util.List; pub

  • Spring Boot @Scheduled定时任务代码实例解析

    假设我们已经搭建好了一个基于Spring Boot项目,首先我们要在Application中设置启用定时任务功能@EnableScheduling. 启动定时任务 package com.scheduling; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframewo

  • Java byte数组操纵方式代码实例解析

    字节数组的关键在于它为存储在该部分内存中的每个8位值提供索引(快速),精确的原始访问,并且您可以对这些字节进行操作以控制每个位. 坏处是计算机只将每个条目视为一个独立的8位数 - 这可能是你的程序正在处理的,或者你可能更喜欢一些强大的数据类型,如跟踪自己的长度和增长的字符串 根据需要,或者一个浮点数,让你存储说3.14而不考虑按位表示. 作为数据类型,在长数组的开头附近插入或移除数据是低效的,因为需要对所有后续元素进行混洗以填充或填充创建/需要的间隙. java官方提供了一种操作字节数组的方法-

  • Spring实例化bean的方式代码详解

    通过这篇文章通过实例代码向大家介绍了Spring实例化bean的几种方法,接下来看看具体内容吧. 1.使用类构造器实现实例化(bean的自身构造器) <bean id = "orderService" class="cn.itcast.OrderServiceBean"/> 2.使用静态工厂方法实现实例化 <bean id = "personService" class = "cn.itcast.OrderFactor

  • Spring AOP的五种通知方式代码实例

    这篇文章主要介绍了Spring AOP的五种通知方式代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 AOP的五种通知方式: 前置通知:在我们执行目标方法之前运行(@Before) 后置通知:在我们目标方法运行结束之后,不管有没有异常(@After) 返回通知:在我们的目标方法正常返回值后运行(@AfterReturning) 异常通知:在我们的目标方法出现异常后运行(@AfterThrowing) 环绕通知:目标方法的调用由环绕通知决定

  • spring cloud gateway网关路由分配代码实例解析

    这篇文章主要介绍了spring cloud gateway网关路由分配代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1, 基于父工程,新建一个模块 2,pom文件添加依赖 <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-

  • JDK线程池和Spring线程池的使用实例解析

    这篇文章主要介绍了JDK线程池和Spring线程池的使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 JDK线程池和Spring线程池实例,异步调用,可以直接使用 (1)JDK线程池的使用,此处采用单例的方式提供,见示例: public class ThreadPoolUtil { private static int corePoolSize = 5; private static int maximumPoolSize = 10;

  • spring事务异常回滚实例解析

    最近遇到了事务不回滚的情况,我还考虑说JPA的事务有bug?我想多了....... 为了打印清楚日志,很多方法我都加tyrcatch,在catch中打印日志.但是这边情况来了,当这个方法异常时候日志是打印了,但是加的事务却没有回滚. 例: 类似这样的方法不会回滚(一个方法出错,另一个方法不会回滚): if(userSave){ try { userDao.save(user); userCapabilityQuotaDao.save(capabilityQuota); } catch (Exce

  • spring强行注入和引用实例解析

    这篇文章主要介绍了spring强行注入和引用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 前提: public class DataProviderManagerImpl implements ApplicationContextAware @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansExc

  • springboot使用事物注解方式代码实例

    这篇文章主要介绍了springboot使用事物注解方式代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考 1.在启动类Application中添加注解@EnableTransactionManagement import tk.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springfra

随机推荐