我爱编程

Spring学习-2

2017-01-04  本文已影响0人  cp_insist

引言:本篇文章是紧接着上一篇文章Spring1做的学习笔记,主要用来供自己复习;

一:spring注解配置方式(IOC注入对象的另外一种形式)

使用之前需要在相应的配置文件配置

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:annotationconfig/> 
将隐式地向Spring 容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor 、 PersistenceAnnotationBeanPostProcessor 以及RequiredAnnotationBeanPostProcessor 这4 个BeanPostProcessor 。
<context:component-scanbase-package="com.casheen.spring.annotation">
<context:exclude-filtertype="regex"
expression="com.casheen.spring.annotation.web..*"/>
</context:component-scan>

• 注解的过滤方式举例:

<context:component-scan base-package="com.netqin">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service"/>
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>

二:spring注解种类(IOC注入对象的另外一种形式)

注解分为在类上使用的注解和方法上使用的注解以及属性上使用的注解;他们的主要目的都是实现对象的自动注入;

1:@Component:它是Spring通用的注解
2:@Repository一般用来加在dao层的注解
3:@Service一般用来加在Service层上面的注解
4:@Controller 一般用来加在控制层即表示层注解

使用@Component注解定义的Bean,默认的名称(id)是小写开头的非限定类名。如这里定义的Bean名称就是userDaoImpl。你也可以指定Bean的名称: @Component("userDao") @Component是所有受Spring管理组件的通用形式,Spring还提供了更加细化的注解形式:@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。目前版本(2.5)中,这些注解与@Component的语义是一样的,完全通用,在Spring以后的版本中可能会给它们追加更多的语义。所以,我们推荐使用@Repository、@Service、@Controller来替代@Component。

5:@Autowired
         • 例如
         @Autowired
         private ISoftPMService softPMService;
         • 或者 @Autowired(required=false)
         private ISoftPMService softPMService = new SoftPMServiceImpl();
6: @Resource
7:@Scope
• 例如         
@Scope("session")  
@Repository()
public class UserSessionBean implementsSerializable {}

• 说明
在使用XML 定义Bean 时,可以通过bean 的scope 属性来定义一个Bean 的作用范围,
同样可以通过@Scope 注解来完成

   @Scope中可以指定如下值:

   singleton:定义bean的范围为每个spring容器一个实例(默认值)

   prototype:定义bean可以被多次实例化(使用一次就创建一次)

   request:定义bean的范围是http请求(springMVC中有效)

   session:定义bean的范围是http会话(springMVC中有效)

   global-session:定义bean的范围是全局http会话(portlet中有效)
8:@Required
        • 例如
         @required              
         public setName(String name){} 
   ```     
  + 说明
     @ required 负责检查一个bean在初始化时其声明的 set方法是否被执行, 当某个被标注了 @Required 的 Setter方法没有被调用,则Spring 在解析的时候会抛出异常,以提醒开发者对相应属性进行设置。
@Required 注解只能标注在Setter 方法之上。因为依赖注入的本质是检查 Setter 方法是否被调用了,而不是真的去检查属性是否赋值了以及赋了什么样的值。如果将该注解标注在非setXxxx() 类型的方法则被忽略。

#####9:@Qualifier

例如
@Autowired
@Qualifier("softService")
private ISoftPMService softPMService;

 + 说明
使用@Autowired 时,如果找到多个同一类型的bean,则会抛异常,此时可以使用 @Qualifier("beanName"),明确指定bean的名称进行注入,此时与 @Resource指定name属性作用相同。


##### 10:@RequestMapping

@Controller
@RequestMapping("/bbtForum.do")
public class BbtForumController {
@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(int topicId,User user) {}
}
• 方法
@RequestMapping("/softpg/downSoftPg.do")
@RequestMapping(value="/softpg/ajaxLoadSoftId.do",method = POST)
@RequestMapping(value = "/osu/product/detail.do", params = { "modify=false" }, method =POST)

  • 说明
    @RequestMapping 可以声明到类或方法上

@Controller
@RequestMapping("/bbtForum.do")
public class BbtForumController {
@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(int topicId,User user) {}
}

+ 参数绑定说明
如果我们使用以下的 URL 请求:
http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tom
topicId URL 参数将绑定到 topicId 入参上,而 userId 和 userName URL 参数将绑定到 user 对象的 userId 和 userName 属性中。和 URL 请求中不允许没有 topicId 参数不同,虽然 User 的 userId 属性的类型是基本数据类型,但如果 URL 中不存在 userId 参数,Spring 也不会报错,此时 user.userId 值为 0 。如果 User 对象拥有一个 dept.deptId 的级联属性,那么它将和 dept.deptId URL 参数绑定。


#####11:@RequestParam
 + 
参数绑定说明
```
@Controller 
@RequestMapping("/bbtForum.do")
public class BbtForumController {
       @RequestMapping(params = "method=listBoardTopic")
       public String listBoardTopic(int topicId,User user) {}
}

@RequestParam("id")
http://localhost/bbtForum.do?method=listBoardTopic&id=1&userId=10&userName=tom
listBoardTopic(@RequestParam("id")int topicId,User user) 中的 topicId 绑定到 id 这个 URL 参数, 那么可以通过对入参使用 @RequestParam 注解来达到目的
@RequestParam(required=false):参数不是必须的,默认为true
@RequestParam(value="id",required=false)
请求处理方法入参的可选类型

1:• void
此时逻辑视图名由请求处理方法对应的 URL 确定,如以下的方法:
@RequestMapping("/welcome.do")
public void welcomeHandler() {}
对应的逻辑视图名为 “ welcome ” 
2:• String
此时逻辑视图名为返回的字符,如以下的方法:
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
Owner owner = this.clinic.loadOwner(ownerId);
model.addAttribute(owner);
return "ownerForm";
}
对应的逻辑视图名为 “ ownerForm ” 
3:• org.springframework.ui.ModelMap
和返回类型为 void 一样,逻辑视图名取决于对应请求的 URL ,如下面的例子:
@RequestMapping("/vets.do")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
对应的逻辑视图名为 “ vets ” ,返回的 ModelMap 将被作为请求对应的模型对象,可以在 JSP 视图页面中访问到。
4:• ModelAndView
当然还可以是传统的 ModelAndView 。
12:@ModelAttribute

• 作用域:request
• 例如

 @RequestMapping("/base/userManageCooper/init.do")
 public String handleInit(@ModelAttribute("queryBean") ManagedUser sUser,Model model,){
  • 或者
 @ModelAttribute("coopMap")// 将coopMap 返回到页面
 public Map<Long,CooperatorInfo> coopMapItems(){}

• 说明

@ModelAttribute 声明在属性上,表示该属性的value 来源于model 里"queryBean" ,并被保存到model 里@ModelAttribute声明在方法上,表示该方法的返回值被保存到model 里

13:@Configuration

该注解主要目的是为了减少spring中的配置文件的内容;
用@Configuration注解该类,等价 与XML中配置beans;
用@Bean标注方法等价于XML中配置bean。
@Bean里面可以加初始化该Bean时的init方法或者destory方法;

三:一个Bean的生命周期:

1:创建BeanFactoryPostProcessor接口的实现类对象myBeanFactoryPostProcessor
2:调用了myBeanFactoryPostProcessor的postProcessBeanFactory方法

package springBeanTest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public MyBeanFactoryPostProcessor() {
        super();
        System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
            throws BeansException {
        System.out
                .println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");
        //这里我们可以通过ConfigurableListableBeanFactory 对象获取到我们需要创建的Bean对象对其进行一定的操作
        BeanDefinition bd = arg0.getBeanDefinition("person");
        bd.getPropertyValues().addPropertyValue("phone", "110");
    }
}

3:创建了实现InstantiationAwareBeanPostProcessorAdapter接口的类的对象
4:调用了InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法

package springBeanTest;

import java.beans.PropertyDescriptor;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;

public class MyInstantiationAwareBeanPostProcessor extends
        InstantiationAwareBeanPostProcessorAdapter {

    public MyInstantiationAwareBeanPostProcessor() {
        super();
        System.out
                .println("这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!");
    }

    // 接口方法、实例化Bean之前调用
    @Override
    public Object postProcessBeforeInstantiation(Class beanClass,
            String beanName) throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
        return null;
    }

    // 接口方法、实例化Bean之后调用
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");
        return bean;
    }

    // 接口方法、设置某个属性时调用
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs,
            PropertyDescriptor[] pds, Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");
        return pvs;
    }
}

5:调用了我们要创建的Bean对象的构造方法:
6:InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
7:注入Person对象的相关属性
8:【BeanNameAware接口】调用BeanNameAware.setBeanName()方法设置容器创建的Bean的名称
9:【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()设置Beanfactory对象
10:BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!
11:【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
12:BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
13:InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法

package springBeanTest;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
 * spring中有大量的aware(感知)接口,实现他们主要使用获取一些相关的资源的;
 * BeanFactoryAware 实现该接口主要是用来获取Beanfactory对象的;
 * BeanNameAware 可以获取bean的Name
 * @author qsk
 */
public class Person implements BeanFactoryAware, BeanNameAware,
        InitializingBean, DisposableBean {
    private String name;
    private String address;
    private int phone;

    private BeanFactory beanFactory;
    private String beanName;

    public Person() {
        System.out.println("【构造器】调用Person的构造器实例化");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("【注入属性】注入属性name");
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        System.out.println("【注入属性】注入属性address");
        this.address = address;
    }

    public int getPhone() {
        return phone;
    }

    public void setPhone(int phone) {
        System.out.println("【注入属性】注入属性phone");
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Person [address=" + address + ", name=" + name + ", phone="
                + phone + "]";
    }

    // 这是BeanFactoryAware接口方法
    @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        System.out
             .println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
        this.beanFactory = arg0;
    }

    // 这是BeanNameAware接口方法
    @Override
    public void setBeanName(String arg0) {
        System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");
        this.beanName = arg0;
    }

    // 这是InitializingBean接口方法
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out
                .println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");
    }

    // 这是DiposibleBean接口方法
    @Override
    public void destroy() throws Exception {
        System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");
    }

    // 通过<bean>的init-method属性指定的初始化方法
    public void myInit() {
        System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");
    }

    // 通过<bean>的destroy-method属性指定的初始化方法
    public void myDestory() {
        System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
    }
}
3:创建了BeanPostProcessor接口的对象

package springBeanTest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {

public MyBeanPostProcessor() {
    super();
    System.out.println("这是BeanPostProcessor实现类构造器!!");
    // TODO Auto-generated constructor stub
}

@Override
public Object postProcessAfterInitialization(Object arg0, String arg1)
        throws BeansException {
    System.out
    .println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");
    return arg0;
}

@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
        throws BeansException {
    System.out
    .println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");
    return arg0;
}

}

1:这是BeanFactoryPostProcessor实现类构造器!!
2:BeanFactoryPostProcessor调用postProcessBeanFactory方法
3:这是BeanPostProcessor实现类构造器!!
4:这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!
5:InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法
6:【构造器】调用Person的构造器实例化
7:InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
【注入属性】注入属性name
【注入属性】注入属性address
【注入属性】注入属性phone
8:【BeanNameAware接口】调用BeanNameAware.setBeanName()
9:【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
10:BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!
11:【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
12:BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
13:InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法
14:容器初始化成功
15:获得对象Person [address=陕西省铜川市, name=cp, phone=110]
16:现在开始关闭容器!
17:【DiposibleBean接口】调用DiposibleBean.destory()
上一篇 下一篇

猜你喜欢

热点阅读