注解:用来代替配置xml文件
spring注解:
1.创建bean
@Component("“id名”) -----
@Service ------web层
@Controller ------应用控制层
@Repository ------dao层
以上的三个注解是相同的作用,但是使用在不同的层。便于后期的维护。
就相当于xml 文件中的
2.属性注入
@AutoWired ======== 按照类型注入
@Resource ======== <bean auotWire="byname"> 按照id注入,当目标类的属性名和bean的id相同时才会注入
@Autowired ======== <bean auotWire="byname"> 当多个相同的bean时,先按类型再按id注入
@Qualifier("author")
注:以上的注解只能用来注解其他的bean类型,集合类型不能用注解来注入。
基本类型和String类的注入:
@value用于注入基本类型,String类行的值
@scope用于注入bean的作用范围,取值和xml文件中的一样
@Bean 将一个对象放入spring的容器中
完全不使用xml文件来配置spring 方法之一
配置一个config类使用 @ComponectScan注解 spring会自动注解,此注解的值是要扫面ode包名
例:
package com.spring.autoWire;
import org.springframework.stereotype.Service;
/**
* @author 刘棋军
* @date2019-01-23
*/
@Service
public class Author {
String name ;
public void setName(String name){
this.name = name;
}
@Override
public String toString() {
return name;
}
}
package com.spring.autoWire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author 刘棋军
* @date2019-01-23
*/
@Component
public class Course {
private String name;
Author author;
public void say(){
System.out.println(name+" "+author.toString());
}
@Resource
public void setName(String name) {
this.name = name;
}
}