Open cccreator opened 6 years ago
@Override是伪代码,表示重写(当然不写也可以),不过写上有如下好处: 1、可以当注释用,方便阅读; 2、编译器可以给你验证@Override下面的方法名是否是你父类中所有的,如果没有则报错。例如,你如果没写@Override,而你下面的方法名又写错了,这时你的编译器是可以编译通过的,因为编译器以为这个方法是你的子类中自己增加的方法。
举例:在重写父类的onCreate时,在方法前面加上@Override 系统可以帮你检查方法的正确性。 @Override public void onCreate(Bundle savedInstanceState)
{…….} 这种写法是正确的,如果你写成:
@Override public void oncreate(Bundle savedInstanceState) {…….} 编译器会报如下错误:The method oncreate(Bundle) of type HelloWorld must override or implement a supertype method,以确保你正确重写onCreate方法(因为oncreate应该为onCreate)。而如果你不加@Override,则编译器将不会检测出错误,而是会认为你为子类定义了一个新方法:oncreate
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("xxx")
public class ItemsServiceImpl implements ItemsService {
@Autowired
private ItemsMapper itemsMapper;
}
public class ItemsController {
@Resourse(“xxx”)
private ItemsService itemsService;
}
@Autowired注解
在使用@Autowired注解之前,我们需要在xml文件中配置一下:
其中
<context:annotation-config/>
这个配置隐式注册了多个对注解进行解析处理的处理器:例如:
如果你想使用@Autowired注解,必须先在Spring容器中声明
AutowiredAnnotationBeanPostProcessor Bean。传统的声明方式如下:
<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/>
如果想使用@Resource 、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor,传统的方式如下:
<bean class="org.springframework.beans.factory.annotation. CommonAnnotationBeanPostProcessor"/>
如果想使用@Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。传统的声明方式如下:
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
一般来说,这些注解我们还是比较常用,尤其是Antowired的注解,在自动注入的时候更是经常使用,所以如果总是需要按照传统的方式一条一条配置显得有些繁琐和没有必要,于是spring给我们提供
<context:annotation-config/>
的简化配置方式,自动帮你完成声明。 不过,我们使用注解一般都会配置扫描包路径选项<context:component-scan base-package=”XX.XX”/>
该配置项其实也包含了自动注入上述processor的功能,因此当使用<context:component-scan/>
后,就可以将<context:annotation-config/>
移除了。比如:<context:component-scan base-package="carPoolingController, carPoolingService, carPoolingDao" />
就把controller包下 service包下 dao包下的注解全部扫描了 修改以上配置文件的头信息后,我们就可以在Java代码通过注解方式来注入bean,看下面代码@Resource
配置文件添加如下信息:
public class StudentService3 implements IStudentService { //@Autowired放在此处也是可行的 private IStudentDao studentDao;
private String id;
public void setId(String id) { this.id = id; } @Autowired//通过此注解完成从spring配置文件中 查找满足studentDao类型的bean//@Qualifier("studentDao")则按照名称经行来查找转配的 public void setStudentDao(IStudentDao studentDao) { this.studentDao = studentDao; }
public void saveStudent() { studentDao.saveStudent(); System.out.print(",ID 为:"+id); } }
private JdbcTemplate JdbcTemplate; @Autowired public LoginContriller (JdbcTemplate JdbcTemplate){ this.jdbcTemplate=jdbcTemplate }
private JdbcTemplate JdbcTemplate; @Autowired public void setjdbcTemplate(JdbcTemplate JdbcTemplate){ this.jdbcTemplate=jdbcTemplate }
@Autowired private JdbcTemplate JdbcTemplate;