在我们Java开发中,Spring Ioc容器(ApplicationContext)负责创建bean,并通过容器将功能类Bean注入到所需要的bean中,xml配置,注解配置还是Java配置都称为配置元数据,元数据就是描述数据的数据,Spring容器解析这些配置元数据进行bean初始化 ,配置,管理依赖。
声明Bean的注解:以下四个注解是等效的,只是在不同的逻辑层使用对应的注解比较一目了然
@Component组件,没有明确的角色,可以代表后面三个注解
@Service 在业务逻辑层(service层)使用
@Repository 在数据访问层(dao层)使用
@Controller 在表现层(MVC-->SpringMVC)使用
注入bean的注解:
@Autowired:spring提供的注解
@Inject:jsr-330提供的注解
@Resource:jsr-250提供的注解
@Autowired @Inject @Resource可以注解在set方法上或者属性上面,建议将注解使用在属性上,有时就是代码更少,层次更清晰
具体项目实践如下:以下所有的类均在同一个包下
package com.itcast.springboot.annotation;
import org.springframework.stereotype.Service;
@Service
public class FunctionService {
public String sayHello(String word){
return "hello world !spring Annotation!"+word;
}
}
package com.itcast.springboot.annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UseFunctionService {
@Autowired
FunctionService functionService;
public String sayHello(String word){
return functionService.sayHello(word);
}
}
只是实践注解配置类,实际并没有配置什么
package com.itcast.springboot.annotation;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.itcast.springboot.annotation")
public class DIConfig {
}
package com.itcast.springboot.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
public class SpringApp {
public static void main(String[] args) {
ApplicationContext context=new AnnotationConfigApplicationContext(DIConfig.class);
UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);
System.out.println(useFunctionService.sayHello("di"));
((AbstractApplicationContext) context).close();
}
}
运行结果:
此次就把上几篇博客里面没有提到的常用的比较重要的注解都解释了一遍。注解会用之后会发现写的代码很简洁。
以上是分析的还是注解配置,不过Java配置也是springboot中比较推荐的一种方式,其实现方式是通过@Configuration和@Bean
使用Java配置和注解混合配置是根据项目中不同的场合采取的比较灵活的一种配置方式,至于什么地方使用Java配置,什么场合使用注解:
今天的内容就分析了Java配置和注解,下一期讲一下Spring AOP面向切面的内容。
不急跬步无以至千里,不积小流无以成江海,质变的前提需要量变。