Spring之bean的实例化和依赖注入

最近天天看spring springboot,脑袋里面早已经神仙打架,一团浆糊,知道了A怎么用,B也可以这么用,然就一团浆糊,好痛苦啊,我天天在想造出这个轮子的人究竟是何方神圣。

bean的解释:在 Spring 中,构成应用程序主干并由Spring IoC容器管理的对象称为bean。bean是一个由Spring IoC容器实例化、组装和管理的对象。
总结:
1.bean是对象,一个或者多个不限定
2.bean由Spring中一个叫IoC的东西管理
3.我们的应用程序由一个个bean构成

xml配置三种实例化Bean的方式
1.使用类构造器实例化(默认无参数)

<bean id=“personService" class="cn.itcast.bean.impl.PersonServiceImpl"/>

2.使用静态工厂方法实例化

xml:
<bean id="personService" 
         class="com.itcast.factory.PersonServiceFactory"    factory-method="createPersonService" />
java代码块:
 public class PersonServiceFactory {
       public  static PersonService createPersonService(){
                 return new PersonServiceImpl();
       }
 }

3.使用实例工厂方法实例化

xml:
<bean id=“personServiceFactory" class="com.itcast.factory.PersonServiceFactory"/>
  <bean id="personService" factory-bean=“personServiceFactory" 
                                                                          factory-method="createPersonService" />
java代码块:
 public class PersonServiceFactory {
        public  PersonService createPersonService(){
                      return new PersonServiceImpl();
        }
 }

依赖注入
当某个角色(可能是一个Java实例,调用者)需要另一个角色(另一个Java实例,被调用者)的协助时,在 传统的程序设计过程中,通常由调用者来创建被调用者的实例。但在Spring里,创建被调用者的工作不再由调用者来完成,因此称为控制反转;创建被调用者 实例的工作通常由Spring容器来完成,然后注入到调用者中

  • Bean的xml注入方式

1、构造方法注入
在这里插入图片描述
2、setter方法注入

(1)普通属性

在这里插入图片描述
(2)对象属性
在这里插入图片描述

  • 实际项目中使用的依赖注入,使用xml方式配置定时任务
    applicationContext-schecule.xml
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:p="http://www.springframework.org/schema/p"
      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-2.0.xsd
                          http://www.springframework.org/schema/context
                          http://www.springframework.org/schema/context/spring-context-2.0.xsd">
   <!-- 하나.주기적으로 실행될 클래스 설정 -->
   <!-- property name은 jobClass로 fix, value는 사용자가 작성한 class 파일 위치 -->
   <bean id="idCardQuartzJob" class="org.springframework.scheduling.quartz.JobDetailBean">
   	<property name="myJob" value="com.mytest.job.DrJob"/>  <!--setter 注入-->
   </bean>
   
   <bean id="myJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
   	<property name="jobDetail" ref="myJob"/> <!--普通属性注入-->
   	<property name="cronExpression" value="0 */5 * * * ?"/><!--对象属性注入-->
   </bean>		
   
   <!--셋. 실제 동작하게끔 설정 -->
   <!--ref bean은 위에서 설정한 interval time 아이디를 넣어주면 됨  -->
   <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
   	<property name="triggers">
   		<list>   <!--list属性注入-->		 
   		<ref bean="myJobTrigger"/>
   		</list>
   	</property>
   	<!-- Quartz -->
   	<property name="quartzProperties">
   		<props> <!--map属性注入-->
   		<prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
   			<prop key="org.quartz.threadPool.threadCount">5</prop>
   			<prop key="org.quartz.threadPool.threadPriority">4</prop>
   			<prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>
   			<prop key="org.quartz.jobStore.misfireThreshold">60000</prop>
   		</props>
   	</property>
   </bean>
</beans>
  • 总结
    依赖注入就是通过配置文件解决代码问题

注解方式
一、使用注解定义Bean
Component 描述Spring框架中Bean
除了@Component外,Spring提供了3个功能基本和@Component等效的注解
@Repository 用于对DAO实现类进行标注
@Service 用于对Service实现类进行标注
@Controller 用于对Controller实现类进行标注
这三个注解是为了让标注类本身的用途清晰,Spring在后续版本会对其增强

二、自动装配Bean

1、普通属性
//set info的值 普通属性注入
@Value(value=“itcast”)
private String info;

2、对象属性

(1)使用@Autowired 进行自动注入,@Autowired 默认按照类型进行注入,如果存在两个相同Bean类型相同,则按照名称注入
@Service (service层),@Repsitory(dao层),@Controller(controller层),@Component(普通类)都是实例化对象后交给IoC容器进行管理
@Autowired 按类型进行属性对象注入
在这里插入图片描述
通过@Autowired的required属性,设置一定要找到匹配的Bean
使用@Qualifier指定注入Bean的名称
使用Qualifier 指定Bean名称后,注解Bean必须指定相同名称
在这里插入图片描述
(2)使用@Resource注入
按名称进行注入
上面等价于@Resource(name=“uDAO”)

@Configuration和@Bean的用法和理解

1、第一种自己写的类,Controller,Service。 用@controller @service即可

2、第二种,集成其它框架,比如集成shiro权限框架,集成mybatis分页插件PageHelper,第三方框架的核心类都要交于Spring大管家管理

@Configuration可理解为用spring的时候xml里面的标签

@Bean可理解为用spring的时候xml里面的标签

Spring Boot不是spring的加强版,所以@Configuration和@Bean同样可以用在普通的spring项目中,而不是Spring Boot特有的,只是在spring用的时候,注意加上扫包配置

<context:component-scan base-package=“com.xxx.xxx” />,普通的spring项目好多注解都需要扫包,才有用,有时候自己注解用的挺6,但不起效果,就要注意这点。

Spring Boot则不需要,主要你保证你的启动Spring Boot main入口,在这些类的上层包就行

用@Bean注解的方法:会实例化、配置并初始化一个新的对象,这个对象会由spring IoC 容器管理。

实例:

@Configuration
public class AppConfig {
 
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
 
}

生成对象的名字:默认情况下用@Bean注解的方法名作为对象的名字。但是可以用 name属性定义对象的名字,而且还可以使用name为对象起多个名字

@Configuration
public class AppConfig {
 
    @Bean(name = "myFoo")
    public Foo foo() {
        return new Foo();
    }
 
}
@Configuration
public class AppConfig {
 
    @Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" })
    public DataSource dataSource() {
        // instantiate, configure and return DataSource bean...
    }
 
}

@Bean 一般和 @Component或者@Configuration 一起使用:@Component和@Configuration不同之处

在 @Component 注解的类中不能定义 类内依赖的@Bean注解的方法。@Configuration可以。

就像这样,DemoApplication是启动类,关于启动类的位置放置,在另一篇博客有专门的去分析。

@Configuration和@Bean的Demo类

@Configuration  
public class ExampleConfiguration {  
  
    @Value("com.mysql.jdbc.Driver")  
    private String driverClassName;  
  
    @Value("jdbc://xxxx.xx.xxx/xx")  
    private String driverUrl;  
  
    @Value("${root}")  
    private String driverUsername;  
  
    @Value("123456")  
    private String driverPassword;  
  
    @Bean(name = "dataSource")  
    public DataSource dataSource() {  
        BasicDataSource dataSource = new BasicDataSource();  
        dataSource.setDriverClassName(driverClassName);  
        dataSource.setUrl(driverUrl);  
        dataSource.setUsername(driverUsername);  
        dataSource.setPassword(driverPassword);  
        return dataSource;  
    }  
  
    @Bean  
    public PlatformTransactionManager transactionManager() {  
        return new DataSourceTransactionManager(dataSource());  
    }  
  
}

这样,在项目中

@Autowired

private DataSource dataSource;

的时候,这个dataSource就是我们在ExampleConfiguration中配的DataSource

写到这儿感觉稍稍的理解了一点点儿,大部部分都是参考的,参考地址:
https://www.cnblogs.com/yss818824/p/12289868.html
https://blog.csdn.net/u013360022/article/details/51824674

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值