spring之java配置

java配置是通过@Configuration和@Bean来实现的

@Configuration:声明当前类是一个配置类,相当于一个spring配置的xml文件

@Bean:注解在方法上面,声明当前方法的返回值为一个Bean

全局配置使用 java配置(如数据库相关配置,mvc相关配置),业务Bean的配置使用注解配置

/**
 * 此处没有使用@Service声明Bean
 *
 * @author Holley
 * @create 2018-07-06 10:50
 **/
public class HelloService {
    public String sayHello(String name) {
        return "Hello " + name + "!";
    }
}
/**
 * 此处没有使用@Service声明Bean,也没有使用@Autowired注入Bean
 *
 * @author Holley
 * @create 2018-07-06 11:32
 **/
public class UseHelloService{

    private HelloService helloService;

public void setSayHello(HelloService helloService) { this.helloService = helloService; }
public String useSayHello(String name) { return helloService.sayHello(name); }
}
/**
 * 此处没有使用包扫描,因为所有的bean都在此类中定义了.
* Bean的名称就是方法名 * 注入HelloService的Bean时,直接调用helloService()方法 *
@author Holley * @create 2018-07-06 11:39 **/ @Configuration public class MyConfig { @Bean public HelloService helloService(){ return new HelloService(); } @Bean public UseHelloService useHelloService(){ UseHelloService useHelloService = new UseHelloService(); useHelloService.setSayHello(helloService()); return useHelloService; }
// 另外一种注入方式,直接将HelloService作为参数给useHelloService().在spring容器中,只要存在某个Bean,就可以在另外一个Bean的声明方法的参数中注入。如:
    /* @Bean
    public UseHelloService useHelloService(HelloService helloService){ 
UseHelloService useHelloService = new UseHelloService();
useHelloService.setSayHello(helloService);
return useHelloService;
}*/
}
public class Test {
    public static void main(String[] args){
        // 使用AnnotationConfigApplicationContext作为spring容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        UserHelloService userHelloService = context.getBean(UserHelloService.class);
        System.out.println(userHelloService.useSayHello("holley"));
        context.close();
    }
}

 

posted on 2018-07-06 14:01  永不宕机  阅读(207)  评论(0编辑  收藏  举报

导航