注解一
今日注解:
代替配置文件:@Configuration @ComponentScan("com.zzw") @Import(JdbcConfig.class)
@PropertySource("classpath:jdbc.properties")
创建对象:自己写的:@Controller @Service @Repository @Component
别人写的:@Bean
给对象属性赋值--注入:@Autowired @Qualifier @Resource @Value
其他:@Scope:单例 多例 request @PostConstruct:在构造函数执行之后执行
@PreDestory:在容器销毁之前执行
一、代替配置文件
配置类:
1.@Configuration
作用:代替beans.xml @Configuration: 只要一个类上面标注了@Configuration, 那么它就是spring的配置类,且可以多个 @Configuration
2.@ComponentScan("com.zzw")
扫描包:
<!-- 扫描com.zzw下面所有的类,如果这个类上有Controller Service Repository Component注解
,就new出来,放容器-->
<context:component-scan base-package="com.zzw"></context:component-scan>
在config包中的SpringConfig类下注解, @ComponentScan("com.zzw") 即可代替上面的扫描包
3.@PropertySource("classpath:jdbc.properties")
引入配置文件:
@PropertySource("classpath:jdbc.properties")
4.@Import(JdbcConfig.class)
导入其他配置类
@Import(JdbcConfig.class)
二、创建对象
把类分类:自己的类可以加注解,别人的类不可以,如果有需要就必须自己写一个类继承后再注解
自己的类
代替:<bean>
下面四个注解,只要放在一个类上,该类的对象就会在容器中了,就是说他们作用相同
建议对应各自相同的层如下:
@Controller @Service @Repository @Component
↓ ↓ ↓ ↓
controller层 service层 dao/mapper层 其他类(除了上面三个之外的类中 )
id默认就是类名首字母小写,可以自定义@Controller("xxx")
别人的类
@Bean,放在方法上,方法返回值对象就会放在容器中
@Bean标注的容器的对象,id就是方法名,可以自定义,@Bean("xxx")
三、给对象属性赋值--注入
代替<property>注入
@Autowired 举例:
@Autowired + @Qualifier = @Resource
1.@Autowired默认类型注入
2.如果找到该类的多个实现类,就按照变量名去匹配id
3.如果变量名一个都匹配不到,就会报错
4.使用@Qualifier指定容器中一个对象,配合@Autowired一起用
5.使用 @Resource注解,根据属性指定一个容器中的对象,效果=@Autowired+@Qualifier
6.@Autowired,@Qualifier都是spring提供的注解,@Resource时Java提供的注解
//@Autowired
//@Qualifier("authorServiceImpl")
@Resource(name = "authorServiceImpl")
private IAuthorService authorService;
注入配置文件的值:
@Value("${xxxx}")
//引入文件
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
@Value("${jdbc.driverClassName}")
String driverClassName;
@Value("${jdbc.url}")
String url;
@Value("${jdbc.username}")
String username;
@Value("${jdbc.password}")
String password;
@Value("${jdbc.maxActive}")
Integer maxActive;
/**
* @Bean标注了的方法,方法的返回值对象就会放在容器中
*/
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxActive(maxActive);
return dataSource;
}
resources 下创建 jdbc.properties
四、其他
@Scope(" "):单例 、多例 、 request 不写后面括号里的内容默认单例
@PostConstruct:在构造函数执行之后执行
@PreDestory:在容器销毁之前执行