Spring框架-3(IOC下)

2017-09-27  本文已影响0人  zhonj

Spring系列文章

Spring框架-1(基础)
Spring框架-2(IOC上)
Spring框架-3(IOC下)
Spring框架-4(AOP)
Spring框架-5(JDBC模板&Spring事务管理)
Spring框架-6(SpringMvc)
Spring框架-7(搭建SSM)
Spring框架-8(SpringMVC2)

上一篇文章使用的XML配置的方法使用Spring的IOC功能。如果Spring每一个类都需要这么麻烦的配置,做起项目来那不累死头牛?所以我们分析一下使用注解的方式来实现。

首先先看下我们需要分析一些什么东西,如下图:


IOC注解.png

注解方式的实现

1.在applicationContext.xml配置文件中开启组件扫描

<context:component-scan base-package="com.zhong.springdemo"/>
<context:component-scan base-package="com.zhong"/>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:contex="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.xsd">
    <contex:component-scan base-package="com.zhong.springdemo"/>
  
</beans>

在使用对象中加上注解

@Component(value="userController") -- 相当于在XML的配置方式中 <bean id="userService" class="...">

//将这个类交个spring管理
@Component("userController")
public class MyController {
    //通过spring把myService注入到这个资源内
    @Autowired
    private MyService myService;

    //测试
    public void test() {
        myService.showTest();
    }
}

//将这个类交个spring管理
@Component("userService")
public class MyService {
    //注入一个属性
    @Value("这是一个测试语句")
    private String textStr;

    //打印注入的属性值
    public void showTest() {
        System.out.println(textStr);
    }
}

编写测试代码

public static void main(String[] args) {
        // 使用Spring的工厂
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 通过工厂获得类:
        MyController myController = (MyController) applicationContext.getBean("userController");
        myController.test();
    }

这是一个测试语句

到这就说明我们的注解方式使用成功了。

总结

Bean管理的常用注解

  1. @Component:组件.(作用在类上)

  2. Spring中提供@Component的三个衍生注解:(功能目前来讲是一致的)

  1. 属性注入的注解(说明:使用注解注入的方式,可以不用提供set方法)

Bean的作用范围和生命周期的注解

  1. Bean的作用范围注解

注解为@Scope(value="prototype"),作用在类上。值如下:

singleton     -- 单例,默认值

prototype     -- 多例
  1. Bean的生命周期的配置(了解)

注解如下:

@PostConstruct    -- 相当于init-method
    
@PreDestroy       -- 相当于destroy-method

好了看到这,我们的IOC暂时基础学完了,下一篇文章我们来分析AOP吧!

上一篇 下一篇

猜你喜欢

热点阅读