- 在Spring4之后,要使用注解开发,必须要保证aop的包导入了
 - 使用注解需要导入context约束,增加注解的支持!
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example.springannotation" />
<context:annotation-config></context:annotation-config>
</beans>
注解的支持:
@Component
public class People {
@Autowired(required = false)
@Value("1235")
private int id;
@Autowired(required = false)
private String name ="ming";
@Value("qing")
public void setName(@Nullable String name) {
this.name = name;
}
}
衍生的注解 @Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!
- dao 【@Repository】
- service【@Service】
- controller【@Controler】
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean。
@Scope("singleton")
xml 与注解:
JAVA的方式配置Spring
import com.example.springannotation.dao.Cat;
import com.example.springannotation.dao.People;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@ComponentScan("com.example.springannotation")
@Import(WwConfig.class)
public class AppConfig {
@Bean
public People getPeople(){
return new People();
}
@Bean
public Cat getCat(){
return new Cat();
}
}
import org.springframework.context.annotation.Configuration;
@Configuration
public class WwConfig {
}
import com.example.springannotation.config.AppConfig;
import com.example.springannotation.dao.People;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@SpringBootTest
class SpringannotationApplicationTests {
@Test
void contextLoads() {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
People people = (People) context.getBean("getPeople");
System.out.println(people.toString());
}
}
|