参考链接
spring注解驱动一
spring注解驱动二
spring注解驱动三
spring注解驱动四
spring注解驱动五
spring注解驱动六
spring注解驱动视频
一、xml配置和注解配置 1.1 xml配置 1.1.1 结构
4.0.0org.examplespring-annotation1.0-SNAPSHOTorg.springframeworkspring-context5.2.6.RELEASEorg.projectlomboklombok1.16.8junitjunit4.12test1.1.3 业务类
@Getter @Setter @NoArgsConstructor @ToString @AllArgsConstructor public class Person { private String name; private Integer age; }1.1.4 测试类
配置类等同于以前的配置文件,只不过一个是java代码的形式,一个是xml配置的形式
package com.best.config; import com.best.bean.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; //配置类==配置文件 @Configuration //告诉Spring这是一个配置类 public class MainConfig { //给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id @Bean(name = "person1") public Person person() { return new Person("lisi", 20); } }1.2.2 测试类
以前是在配置文件中写,component-scan,现在呢,配置类就相当于配置文件,我们只需要在配置类上加上@ComponentScan注解即可
package com.best.controller; import org.springframework.stereotype.Controller; @Controller public class BookController { }
package com.best.dao; import org.springframework.stereotype.Repository; @Repository public class BookDao { }
package com.best.service; import org.springframework.stereotype.Repository; @Repository public class BookService { }
package com.best.config; import com.best.bean.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; @Configuration public class MainConfig2 { /** * 默认都是单实例的 * prototype: 多实例的, ioc容器启动并不会去调用方法创建对象放在容器中。每次获取的时候才会调用方法创建对象。 * singleton: 单实例的(默认值), ioc容器启动会调用方法创建对象放到ioc容器中。以后每次获取就直接从容器(map.get())中拿。 * request: 同一个请求创建一个实例 * session: 同一个session创建一个实例 * @return */ @Scope("prototype") @Bean("person2") public Person person() { System.out.println("给容器中添加Person...."); return new Person("张三", 25); } }
gitee源码