autowire注入
格式
<bean id="" value="" autowire="byName"(or byType)></bean>
注解扫描:
<context:component-scan base-package="要扫描的包" > </context:component-scan>
//扫描该包中的所有的类
<context:component-scan base-package="要扫描的包" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.sterrotype.Controller"/>
</context:component-scan>
//use-default-filters="false"作用不扫描该包里的所有类,
//<context:include-filter type="annotation" expression="org.springframework.sterrotype.Controller">只扫描带Controller的类
<context:component-scan base-package="要扫描的包" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
//context:exclude-filter 不扫描带Controller注解的类
@Component
@Service
@Controller
@Repository
@Service(value="userService")
注解使用格式如上;相当于<bean id = "userService" class="">
在value属性值可以不写,则默认是类的名称首字母小写。
以上四个注解功能相同。
基于注解方式实现属性注入:
@Autowired:根据类型进行自动装配
@Qualifier:根据属性名称进行注入,与Autowired配对使用
@Resource:可以根据类型注入,可以根据名称注入
@Value:注入普通类型属性
以上四种注解写在引入的属性之上,方法之下如:
@Service public class UserService{ @Value(value = "abc" ) private String name @Autowire @Qualifier(value = "...")//名称与UserDao中设置的id相同 private UserDao userDao; }
完全注解开发:
(1).创建配置类文件
@Configuration//作为配置类,代替xml文件
@ComponentScan(basePackages = {"com.ithimes"});
public class SpringConfig{
}
@Test
public void testService2(){
AplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
//配置类变化
}