1、基础配置
要使用注解开发,必须保证导入aop的包!
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="lin.pojo"/>
<context:annotation-config/>
</beans>
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component //等价于在bean里面注册了一个bean,
public class User {
@Value("林XX")
public String name;
}
@Component 这个注解意思为组件,放在类上,表示这个类被Spring管理了,等价于在bean里面注册了一个bean。 @Value("XXX"),这个注解就是属性的注入,相当于bean中的 <property name="name" value="林XX"/>
2、衍生的注解
@Component 有几个衍生的注解,在web开发中,会按照MVC三层架构分层!(四个注解的功能是一样的)
1、dao(数据访问层):@Repository
2、service(业务层):@Service
3、controller(控制层):@Controller
@Repository、@Service、@Controller,这三个注解跟@Component注解是一样的,都代表某个类会被注册到Spring中,不同的层使用不同的注解!
4、作用域
@Scope("singleton") //单例模式 @Scope("prototype") //原子模式
5、以上小结
xml 与 注解:
【1】xml: 更加万能,适用于任何场景! 维护简单方便!
【2】注解:不是自己的类是用不了,维护相对复杂!
xml 与 注解的最佳实践:xml用来管理bean,注解只负责属性的注入。
6、使用Java的方式配置Spring【*】
完全不使用Spring的xml配置,全用java来实现!【这个纯java的配置方式,在SpringBoot中随处可见】
JavaConfig 在Spring 4 之后,它成为了一个核心功能!
案例:
案例框架!
实体类:
@Data @NoArgsConstructor @AllArgsConstructor @Component public class User { @Value("林XX") private String name; }
config包下新建一个AppConfig.java: 注意:@Bean这个注解一定不要漏,否则在Spring容器中找不到这个名为userBean的bean
@Configuration @ComponentScan("lin.pojo") public class AppConfig { //注册一个bean,就相当于我们之前写的一个bean标签 //这个方法的名字就相当于bean中的id //这个方法的返回值就相当于bean标签中的class @Bean public User userBean(){ return new User(); } }
@Configuration 注解下的类也会被Spring容器托管,注册到容器中,因为这个注解本身也是一个@Component注解使用的类!
@Configuration 代表这是一个配置类,跟我们之前使用applicationContext.xml是差不多的
测试类:完全使用配置类方法时,我们只能使用 AnnotationConfigApplicationContext 来获取上下文容器
@Test public void test1(){ ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); User user = (User) context.getBean("userBean"); System.out.println(user); }
结果:
此时,若是有两个@Configuration 配置类,我们使用 @Import注解实现合并!
【1】先在config包下新建一个App2Config.class类
@Configuration
public class App2Config {
@Bean
public Dog dogBean(){
return new Dog();
}
}
【2】然后在AppConfig.class类中使用@Import 注解导入
@Configuration
@ComponentScan("lin.pojo")
@Import(App2Config.class)
public class AppConfig {
@Bean
public User userBean(){
return new User();
}
}
【3】测试:
@Test
public void test1(){
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
User user = (User) context.getBean("userBean");
Dog dog = (Dog) context.getBean("dogBean");
System.out.println(user);
System.out.println(dog);
}