spring04

此部分是将spring的xml配置文件换为java类的配置,公司中使用较多。

1、环境的准备

此次联系比较简单,只有一个类:

  • User
package com.nevesettle.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class User {
    @Value("小明")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

  • @Component 相当于xml中注册bean的那步。
  • @Value("小明") 相当于在bean中进行注入。

2、配置类

package com.nevesettle.config;

import com.nevesettle.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.nevesettle.pojo")
public class MyConfig {

    @Bean
    public User user(){
        return new User();
    }
}
  • @Configuration 表明这是一个配置类
  • @ComponentScan("com.nevesettle.pojo") 表明扫描的包,也就是只对该包里的类进行扫描

3、测试类

import com.nevesettle.config.MyConfig;
import com.nevesettle.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args){
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = context.getBean("user", User.class);
        System.out.println(user.getName());
    }
}
posted @ 2020-03-09 19:29  Nevesettle  阅读(93)  评论(0编辑  收藏  举报