Spring框架基础

Spring是一个开源的轻量级的应用开发框架,其目的是用于简化企业级应用程序的开发,降低侵入性。

Spring本质:管理软件中的对象,创建对象和维护对象之间的关系。

Spring实现了IOC和AOP功能,可以简化Bean对象创建和Bean对象之间的解耦。

Spring容器有BeanFactory和ApplicationContext两种类型。其中ApplicationContext继承自BeanFactory接口。

例如:String conf = "applicationContext.xml";     ApplicationContext ac = new ClassPathXmlApplicationContext(conf);

主要方法:getBean(beanName)获取Bean对象

Spring容器创建Bean对象的方法有3种:

1、用构造器实例化。例如:<bean id="" class=""/>

2、静态工厂方法实例化。 例如:<bean id="" class="" factory-method=""/>

3、对象工厂方法实例化。 例如:<bean id=""    factory-bean=""   factory-method=""/>

bean对象的别名:<alias name=""  alias=""/>

bean对象的作用域:singleton,prototype,request,session,global Session

bean定义的属性:id,name,class,init-method,destroy-method,lazy-init,autowire

<beans>定义的属性:default-init-method,default-destory-method,default-lazy-init

IOC:Inversion of Control,控制反转(程序中对象的获取方式发生反转,由最初的new方式创建,转变为由第三方框架创建,注入(DI),它降低了对象之间的耦合度)

DI:Dependency Injection,依赖注入。(将一起工作具有关系的对象,通过构造方法参数或方法参数传入建立关联,因此容器的工作就是创建bean时注入这些依赖关系)分为:Setter注入,构造器注入。

<bean id="" class="">
      <property name="" value=""/>
</bean>

<bean id="" class="">
     <constructor-arg index="0" value=""/>
</bean>

自动装配(outowire):操作bean对象之间的关联关系。

分为5种:no(默认值),byName,byType,contructor,autodetect

参数值注入:

<property name="name">
      <value></value>
</property>

<property name="name" value=""/>

<property name="" ref=""/>

<property name="lists">
      <list>
              <value></value>
        </list>
</property>

<property name="sets">
      <set>
              <value></value>
        </set>
</property>

<property name="score">
       <map>
             <entry key="" vlaue=""/>
        </map>
</property>

<property name="props">
         <props>
               <prop key=""></prop>
         </props>
</property>

<util:list id="langList">
       <value></value>
</util:list>

<property name="langs" ref="langList">
<util:list>,<util:set>,<util:properties>都可以采用这种方式

<util:properties id="const" location="classpath:const.properties">
<property name="" value="#{msg.name}"/>

注入null值
<property name="name">
     <null/>
</property>

基于注解的组件扫描:

组件扫描可以代替大量的XML配置的<bean>定义。

<context:component-scan base-package="com.model"/>

常用的注解标记:@Component ,@Named,@Repository,@Service,@Controller

生成的bean的默认为类名首字母小写,当然我们可以指定bean的id。例如:@Component("test")

作用域:@Scope("prototype"),

指定初始化和销毁回调方法:@PostConstruct,@PreDestroy

依赖关系的注入:

1、@Autowired / @Qualifier 构造器和Setter注入都可以使用。

例如:

@Autowired

public Test(@Qualifier("test") Test test) {

      this.test = test;

}

注入的对象为单例时,@Quealifier可以省略。

2、@Inject / @Named

3、@Resource 只能处理Setter注入。通常将@Resource注解写在set方法上,如果写在属性上,则只会执行一行代码this.name = name。

4、@Value注解可以注入Spring 表达式的值。例如:@Value("#{const.username}")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值