注解 | 说明 |
@Component | 使用在类上用于实例化Bean |
@Controller | 使用在web层类上用于实例化Bean |
@Service | 使用在service层类上用于实例化Bean |
@Repository | 使用在dao层类上用于实例化Bean |
@Autowired | 使用在字段上用于根据类型依赖注入 |
@Qualifier | 结合@Autowired一起使用用于根据名称进行依赖注入 |
@Resource | 相当于@Autowired+@Qualifier,按照名称进行注入 |
@Value | 注入普通属性 |
@Scope | 标注Bean的作用范围 |
@PostConstruct | 使用在方法上标注该方法是Bean的初始化方法 |
@PreDestroy | 使用在方法上标注该方法是Bean的销毁方法 |
上面那篇文章说过如何用注解 实例化 Bean 和 注入引用数据类型
下面介绍其他几个
1.value 进行普通参数的注入:
public class Demo {
@Value("Hello,World!")
private String parameter;
@Test
public void test(){
System.out.println(parameter);
}
}
这样会输出null 因为没有Spring的参与 他是不会注解的。
我们尝试弄一个Service + ServiceImpl 做实验:【记得Spring配置文件中配置扫描注解的标签】
Service.java :
package com.Service;
public interface TestService {
public void show();
}
ServiceImpl.java :
package com.ServiceImpl;
import com.Service.TestService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service("service")
public class TestServiceImpl implements TestService {
@Value("HelloWorld!") //普通注入参数
private String parameter;
@Override
public void show() {
System.out.println(parameter);
}
}
Demo.java :
import com.ServiceImpl.TestServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
@Test
public void test(){
ApplicationContext app = new ClassPathXmlApplicationContext("app.xml");
TestServiceImpl bean = (TestServiceImpl) app.getBean("service");
bean.show();
}
}
打印:
信息: Loading XML bean definitions from class path resource [app.xml]
HelloWorld!
那么我们直接 String value = "HelloWorld" 不就完了了吗 为什么还要费那么大力气去用啊.
他还有个功能 比如 Spring导入了一个 properties 文件 然后给Spring 配置文件解析,然后我们可以在value注解中 ${} 直接获取到 然后导入。
自己去试试:
类似于:@Value("${name}")
然后:
然后:
后面那几个自己去试试 即可 很好玩的
.
本文来自博客园,作者:咸瑜,转载请注明原文链接:javascript:void(0)p/14924603.html