使用Java配置文件

1.@Configuration

使用注解将Java类变成一个注解文件

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.saxon.config;

import com.saxon.Dao.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class applicationContext {
@Bean
public User user(){
return new User ();
}
}

接下来看一下@Configuration里面的东西:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(
annotation = Component.class
)
String value() default "";

boolean proxyBeanMethods() default true;
}

从我现在的知识储备来看就是一个组件,就是我们上一次讲到的Component;实际上我们自己写的类变成一个组件来配置文件;

2.@Import

就是我们以前说的,把各个部分的xml文件合成一个,可以通过一个主要的xml访问所有的bean;这里也是同样的作用;

3.@ComponentScan
1
@ComponentScan("com.saxon.config")

扫描指定的包下的所有注解,与前面的功能一致;

4.@Bean

使用这个注解,将一个类交给我们的spring托管,相当于xml配置文件的Bean标签;

1
2
3
4
@Bean
public User user(){
return new User ();
}

函数名就是我们的bean标签的id,返回值就是对象 就是class标签;